C++の書き方
よく使う文法・タグ・操作を、短い例で。42項目から探せます。
42 / 42項目
基本の形や関数内の抜粋を掲載しています。そのまま実行する例と準備方法は、各言語の「学ぶ」ページで確認できます。
変数と表示
文字列や整数を覚えます。
std::string name = "海";
std::cout << name << "\n";条件分岐
条件に応じて処理を変えます。
int age = 20;
if (age >= 18) {
std::cout << "成人\n";
} else {
std::cout << "未成年\n";
}繰り返し
forで1から3まで表示します。
for (int i = 1; i <= 3; i++) {
std::cout << i << "\n";
}関数
計算を関数にまとめます。
int add(int a, int b) { return a + b; }配列
同じ型の値を並べます。
int numbers[] = {10, 20, 30};
std::cout << numbers[0] << "\n";構造体
関連する値に名前を付けます。
#include <iostream>
#include <string>
struct User { std::string name; };
int main() {
User user{"海"};
std::cout << user.name << "\n";
}参照
同じ変数の別名を作ります。
int age = 20;
int& same = age;
same = 21;
std::cout << age << "\n";const・auto
定数を作る、型を推論する。
const int limit = 10;
auto name = std::string("海");文字列の操作
長さと部分文字列を使う。
std::string text = "hello";
std::cout << text.size() << "\n";
std::cout << text.substr(0, 2) << "\n";stringとiostreamを読み込みます。
vector
追加できる一覧を作る。
std::vector<int> nums{1, 2};
nums.push_back(3);
std::cout << nums.at(0) << "\n";vectorとiostreamを読み込みます。
map
キーと値の組を保存する。
std::map<std::string, int> ages;
ages["海"] = 20;mapとstringを読み込みます。
範囲for
一覧の値を順番に処理する。
int nums[] = {1, 2, 3};
for (int n : nums) { std::cout << n << "\n"; }while・break
条件で繰り返し、途中で終了する。
int i = 0;
while (i < 3) {
if (i == 2) break;
i++;
}class・コンストラクター
作成時に初期値を決める。
class User {
public:
std::string name;
User(std::string value) : name(value) {}
};stringを読み込みます。
継承・override
既存の型を広げ、処理を置き換える。
struct Animal { virtual void speak() {} };
struct Cat : Animal { void speak() override {} };enum class
候補が決まった型を作る。
enum class Status { Draft, Published };
Status status = Status::Draft;テンプレート
型を変えて使える関数を作る。
template <typename T>
T twice(T value) { return value + value; }ラムダ
小さな関数をその場で作る。
auto add = [](int a, int b) { return a + b; };sort
一覧を並べ替える。
std::vector<int> nums{3, 1, 2};
std::sort(nums.begin(), nums.end());vectorとalgorithmを読み込みます。
例外処理
エラーを投げて受け止める。
try {
throw std::runtime_error("失敗");
} catch (const std::exception& error) {
std::cout << error.what();
}stdexceptとiostreamを読み込みます。
unique_ptr
所有するメモリーを自動で解放する。
auto number = std::make_unique<int>(10);memoryを読み込みます。
ファイルを読む
ファイルから1行ずつ読む。
std::ifstream file("notes.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << "\n";
}fstream・string・iostreamを読み込みます。
キーボードから読む
cinで入力された値を受け取ります。
int age;
if (std::cin >> age) {
std::cout << age << "\n";
}#include <iostream>が必要です。
空白を含む1行を読む
getlineは空白を含めて1行を受け取ります。
std::string name;
std::getline(std::cin, name);#include <iostream>と#include <string>が必要です。
文字を数値にする
stoiやstodで文字列を数値に変えます。
int count = std::stoi("12");
double price = std::stod("3.5");#include <string>が必要です。変換できない値は例外になります。
文字列を検索する
findの結果がnpos以外なら見つかっています。
std::string text = "hello world";
bool found = text.find("world") != std::string::npos;#include <string>が必要です。
一部の文字を取り出す
substrに開始位置と文字数を渡します。
std::string text = "hello";
std::string first = text.substr(0, 2);#include <string>が必要です。
短い条件分岐
条件に応じて使う値を選びます。
int age = 20;
auto label = age >= 18 ? "成人" : "未成年";vectorの追加・削除
末尾への追加と削除を行います。
std::vector<int> scores = {80, 90};
scores.push_back(70);
scores.pop_back();
auto count = scores.size();#include <vector>が必要です。空のvectorにpop_backは使えません。
範囲を確認して取得
atは範囲外なら例外で知らせます。
std::vector<int> scores = {80, 90};
int first = scores.at(0);#include <vector>が必要です。
辞書のキーを確認する
findで存在を調べると新しい要素は追加されません。
std::map<std::string, int> scores = {{"海", 80}};
auto it = scores.find("海");
if (it != scores.end()) {
std::cout << it->second;
}#include <map>、<string>、<iostream>が必要です。
重複しない集合
setには同じ値が重複して入りません。
std::set<int> values = {1, 1, 2};
values.insert(3);#include <set>が必要です。
2つの値をまとめる
構造化束縛で2つの値を別々に受け取ります。
std::pair<int, int> point = {10, 20};
auto [x, y] = point;C++17以降。#include <utility>が必要です。
引数の初期値
省略された引数には決めておいた値が入ります。
int add(int value, int extra = 1) {
return value + extra;
}同じ名前で型を変える
引数の型に合う関数が呼ばれます。
int twice(int value) { return value * 2; }
double twice(double value) { return value * 2; }変更せずに参照する
const参照は元の値を変更せずに受け取れます。
void show(const std::string& name) {
std::cout << name << "\n";
}#include <string>と#include <iostream>が必要です。
値をクラス内で守る
privateの値は外から直接変更できません。
class User {
int age = 20;
public:
int getAge() const { return age; }
};名前をまとめる
名前空間を付けて同じ名前の衝突を防ぎます。
namespace math {
int twice(int x) { return x * 2; }
}
// math::twice(3)で呼ぶ値がない場合も表す
optionalは値の有無を確認して使います。
std::optional<int> score = 80;
if (score) {
std::cout << *score;
}C++17以降。#include <optional>と#include <iostream>が必要です。
ファイルに書く
ofstreamは使い終わると自動でファイルを閉じます。
std::ofstream file("memo.txt");
if (file) {
file << "こんにちは\n";
}#include <fstream>が必要です。既存の内容を上書きします。
配列の値を探す
findで指定した値の位置を調べます。
std::vector<int> values = {1, 2, 3};
auto it = std::find(values.begin(), values.end(), 2);
bool found = it != values.end();#include <algorithm>と#include <vector>が必要です。
空のポインタを確認
nullptrは参照先がないことを表します。
int* ptr = nullptr;
if (ptr != nullptr) {
std::cout << *ptr;
}#include <iostream>が必要です。