WATAPEDIA
--
プログラミング
-- C++
Last updated Aug. 24, 2015
Home
Return
PDFを表示
記事が表示されない場合は,ブラウザが非対応です.
上のPDFを表示をクリックしてください.
comp -MYPEDIA Programing- C++ 1 サンプルコード 文字列を結合 <文字列 1> + <文字列 2> サンプルコード #include
using namespace std; int main() { string str1 = "AAA"; string str2 = "BBB"; string result = str1 + str2; cout << result << endl; return 0; } 数値を文字列に変換 ostringstream <変数名> サンプルコード #include
#include
#include
using namespace std; int main() { ostringstream ss; double number1 = 1234.5678; ss << number1; string str1 = ss.str(); cout << str1 << endl; 1 Programing 一覧へ . ↰. comp -MYPEDIA Programing- ss.clear(); ss.str(""); ss << fixed << setprecision(8) << number1; // 精度を小数点以下 8 桁にす る str1 = ss.str(); cout << str1 << endl; return 0; } メモリ上のアドレスを取り出す &<変数名> サンプルコード #include
using namespace std; int main() { string str = "AAA"; cout << &str << endl; return 0; } ポインタを宣言して代入・参照する サンプルコード #include
using namespace std; int main() { string str = "AAA"; string* ptr = &str; cout << "address: " << ptr << endl; cout << "contents: " << *ptr << endl; 2 Programing 一覧へ . ↰. comp -MYPEDIA Programing- return 0; } 様々な型を引数にできる関数を作る (テンプレート関数) サンプルコード #include
using namespace std; template
void println(typeName out) { cout << out << ’\n’; } int main() { println("Kitty on your lap"); // string を引数にできる println(10); // int も引数にできる println(1.052); // float も引数にできる return 0; } クラスを作る サンプルコード #include
using namespace std; class Human { private: string name; double bmi; public: Human(string name, double height, int weight) { bmi = weight / (height * height); 3 Programing 一覧へ . ↰. comp -MYPEDIA Programing- } // コンストラクタ void showBmi() {cout << bmi << endl; } // BMI を出力するメンバ関数 }; int main(void) { Human *aHuman = new Human("Tom", 1.85, 58); // 新しいオブジェクトの生成 aHuman->showBmi(); // BMI を表示 return 0; } 様々な型に対応したクラスを作る (テンプレートクラス) サンプルコード #include
using namespace std; template
class Human { private: string name; double bmi; public: Human(string name, double height, typeName weight) { bmi = weight / (height * height); } // コンストラクタ void showBmi() {cout << bmi << endl; } // BMI を出力するメンバ関数 }; int main(void) { Human
*aHuman = new Human
("Tom", 1.85, 58.0); // 新 しいオブジェクトの生成 aHuman->showBmi(); // BMI を表示 } 4 Programing 一覧へ . ↰. comp -MYPEDIA Programing- コンストラクタと同時にメンバ変数の初期化 サンプルコード #include
using namespace std; class Human { private: int name; double bmi; public: Human() : name("Default"), bmi(0) // メンバ変数の初期化 { } // コンストラクタ void showBmi() {cout << bmi << endl; } // BMI を出力するメンバ関数 }; int main(void) { Human *aHuman = new Human(); // 新しいオブジェクトの生成 aHuman->showBmi(); // BMI を表示 return 0; } ベクター要素の各要素に for 文でアクセスする サンプルコード #include
#include
using namespace std; int main() { vector
v; 5 Programing 一覧へ . ↰. comp -MYPEDIA Programing- v.push_back(1); v.push_back(2); v.push_back(3); for (auto n: v) { cout << n << ’\n’; } } 正規表現によるマッチを調べる サンプルコード #include
#include
using namespace std; int main() { regex pattern("A.*"); if (regex_match("Aaa", pattern)) cout << "mutch!" << endl; } 6 Programing 一覧へ . ↰.