TopC++ 入門 › 参考 › チートシート

C++ チートシート — 逆引きリファレンス

「やりたいこと → 書き方」の逆引き。キーワード検索 + カテゴリ絞り込み対応。開発中のカンペとしてブックマーク推奨。

すべて
string
vector
map/set
lambda
algorithm
I/O
smart_ptr
C++17
文字列の結合str
s += other;
C 文字列に変換str
s.c_str()
部分文字列str
s.substr(start, len);
検索str
size_t p = s.find("abc"); if (p != npos) ...
逆順str
std::reverse(s.begin(), s.end());
数値→文字列str
std::to_string(42);
文字列→数値str
int n = std::stoi(s);
split(delimiter)str
std::istringstream is(s); for(string t; getline(is,t,',');)
初期値付き生成vec
std::vector<int> v{1,2,3};
N 要素で生成vec
std::vector<int> v(10, 0); // 10 個の 0
末尾に追加vec
v.push_back(x); v.emplace_back(args...);
末尾から削除vec
v.pop_back();
条件で削除vec
v.erase(std::remove_if(v.begin(),v.end(),pred), v.end());
サイズ/空判定vec
v.size(), v.empty()
全要素を巡回vec
for (auto& x : v) { ... }
vector を初期化vec
v.clear();
サイズ変更vec
v.resize(20);
キャパシティ予約vec
v.reserve(1000);
map 生成map
std::map<std::string,int> m;
挿入/上書きmap
m["key"] = 42;
存在確認map
if (m.count("k")) ... // または m.contains (C++20)
順序不問ならmap
std::unordered_map<K,V> (hash map)
set に追加map
s.insert(3);
map 走査map
for (auto& [k,v] : m) { ... }
最小のラムダlmb
auto f = [](int x){ return x*2; };
値キャプチャlmb
[y](int x){ return x+y; }
参照キャプチャlmb
[&y](int x){ y += x; }
全部値 / 全部参照lmb
[=]{...} / [&]{...}
mutablelmb
[y]() mutable { y++; return y; }
std::function に保存lmb
std::function<int(int)> f = [](int x){return x;};
ソートalg
std::sort(v.begin(), v.end());
降順alg
std::sort(v.begin(), v.end(), std::greater<>{});
検索alg
auto it = std::find(v.begin(), v.end(), x);
条件検索alg
std::find_if(v.begin(), v.end(), pred);
個数カウントalg
std::count_if(v.begin(), v.end(), pred);
合計alg
std::accumulate(v.begin(), v.end(), 0LL);
各要素を変換alg
std::transform(in.begin(), in.end(), out.begin(), f);
二分探索alg
std::binary_search(v.begin(), v.end(), x);
最大・最小alg
auto [mn,mx] = std::minmax_element(v.begin(), v.end());
1 行読み込みio
std::string l; std::getline(std::cin, l);
ファイル全行io
std::ifstream f(p); for(std::string l; std::getline(f,l);) ...
書き込みio
std::ofstream o(p); o << "hi\n";
整形出力io
#include <iomanip> cout << std::fixed << std::setprecision(2) << x;
unique_ptr 生成mem
auto p = std::make_unique<T>(args...);
shared_ptr 生成mem
auto p = std::make_shared<T>(args...);
movemem
auto q = std::move(p);
生ポインタ取得mem
T* raw = p.get();
構造化束縛c++17
auto [a, b] = getPair();
optionalc++17
std::optional<int> x = 42; if (x) use(*x);
variantc++17
std::variant<int,string> v; std::visit(visitor, v);
if-initc++17
if (auto it = m.find(k); it != m.end()) ...
range-forc++11
for (const auto& x : v) { ... }
auto 戻り値c++14
auto f(int x) { return x*2; }
constexpr 関数c++11
constexpr int sq(int x) { return x*x; }
thread / asyncc++11
std::thread t([]{...}); t.join();