C++ cheatsheet – syntax overview
103 key commands and patterns for quick reference.
Skeleton & output Types & variables Control flow Functions & references std::string STL containers <algorithm> & <numeric> Classes & OOP Smart pointers & memory Templates, lambdas & modern features Files & errors Compiler flags & tools
Skeleton & output
#include <iostream> | Include a header (standard library in <>, own headers in "") |
int main() { ... } | Entry point of the program |
std::cout << "Text" << x << '\n'; | Output (line break with \n, endl flushes the buffer) |
std::cin >> x; | Read a value from the keyboard |
std::getline(std::cin, zeile); | Read a whole line |
std::cerr << "Error\n"; | Error output (unbuffered) |
// Kommentar /* Block */ | Comments |
std::format("{:>8.2f}", x) | Formatted string (C++20, <format>) |
Types & variables
int double bool char | Basic types (integer, floating-point number, boolean value, character) |
auto x = 42; | Let the compiler deduce the type |
int a{5}; int b{}; | Brace initialization (prevents narrowing; b == 0) |
const int N = 10; | Constant (cannot be changed) |
constexpr int M = 2 * N; | Constant already computed at compile time |
static_cast<double>(i) | Explicit type conversion (instead of a C cast) |
std::size_t std::int64_t | Size type (<cstddef>) and fixed-size integer (<cstdint>) |
sizeof(int) | Size of a type in bytes |
Control flow
if (a > b) { } else if (a == b) { } else { } | Branching |
if (auto it = m.find(k); it != m.end()) { } | if with initialization (C++17) |
for (int i = 0; i < n; ++i) { } | Counting loop |
for (const auto& x : container) { } | Range-for over all elements without copying |
while (bedingung) { } do { } while (b); | Loop with pre-check or post-check, respectively |
break; continue; | Abort the loop / next iteration |
switch (x) { case 1: ...; break; default: ...; } | Multi-way branching (do not forget break) |
x > 0 ? "pos" : "neg" | Ternary operator as an expression |
Functions & references
int f(int a, int b = 2); | Function with default argument (declaration) |
void f(const std::string& s); | Only read large objects: const reference |
void f(int& out); | Reference: the original is changed |
int* p = &x; *p = 5; | Create a pointer to x and dereference it |
int* p = nullptr; | Pointer that points to nothing |
auto [a, b] = paar; | Structured bindings (C++17) |
[[nodiscard]] int f(); | Compiler warns if the return value is ignored |
auto f(int x) -> int { ... } | Trailing return type syntax |
std::string
std::string s = "Text"; s.size() | Create a string, length |
s + " more" s += "!" | Concatenate / append |
s.substr(pos, len) | Substring |
s.find("x") // std::string::npos | Search; npos means not found |
s.replace(pos, len, "new") | Replace a part |
s.empty() s.clear() | Check if empty / clear |
std::stoi(s) std::stod(s) std::to_string(42) | Convert string to number and number to string |
s.starts_with("ab") s.ends_with("yz") | Check beginning/end (C++20) |
std::string_view sv = s; | Non-owning view of text (no copy) |
STL containers
std::vector<int> v{1, 2, 3}; | Dynamic array (default choice) |
v.push_back(4); v.pop_back(); v.emplace_back(5); | Append / remove at the end |
v[i] v.at(i) v.front() v.back() | Access (at checks bounds) |
v.size() v.empty() v.clear() v.reserve(n) | Size, empty, clear, pre-reserve memory |
std::array<int, 5> a{}; | Fixed-size array |
std::map<std::string, int> m; m["a"] = 1; | Sorted map (tree, O(log n)) |
std::unordered_map<std::string, int> um; | Hash map (O(1) on average) |
std::set<int> s; s.insert(3); s.count(3) | Set of unique values |
std::deque<int> std::list<int> std::queue<int> std::stack<int> | Other containers: double-ended queue, linked list, queue, stack |
m.find(k) != m.end() m.contains(k) | Check a key (contains since C++20) |
<algorithm> & <numeric>
std::sort(v.begin(), v.end()); | Sort (with a lambda as the 3rd argument for a custom criterion) |
std::find(v.begin(), v.end(), x) | Find the first occurrence (iterator, otherwise end()) |
std::find_if(b, e, [](int x){ return x > 5; }) | Find the first element that satisfies a condition |
std::count(b, e, x) std::count_if(b, e, pred) | Count |
std::reverse(b, e); | Reverse the order |
std::accumulate(b, e, 0) | Compute the sum (<numeric>) |
std::transform(b, e, out, f) | Apply a function to every element |
std::min_element(b, e) std::max_element(b, e) | Iterator to the smallest/largest element |
std::any_of(b, e, p) std::all_of(b, e, p) std::none_of(b, e, p) | Check a condition for at least one / all / none |
std::erase_if(v, pred); | Delete elements (C++20); formerly: erase(remove_if(...), end) |
std::ranges::sort(v); | Ranges variant without iterators (C++20) |
Classes & OOP
class A { public: ... private: ... }; | Class with access sections (struct: public by default) |
A(int x) : x_(x) {} | Constructor with member initializer list |
~A(); | Destructor (cleans up, basis of RAII) |
int wert() const; | const method: does not modify the object |
class B : public A { ... }; | Public inheritance |
virtual void f(); void f() override; | Virtual method and safe overriding |
virtual void f() = 0; | Pure virtual: abstract class (interface) |
A(const A&) = default; A& operator=(A&&) = delete; | Have special functions generated or forbid them |
static int zaehler; explicit A(int); | Class-wide member; prevents implicit conversion |
Smart pointers & memory
auto p = std::make_unique<T>(args); | Sole ownership, no copying, freed at the end of the scope |
auto q = std::move(p); | Transfer ownership (p is empty afterwards) |
auto s = std::make_shared<T>(args); | Shared ownership with reference counter |
std::weak_ptr<T> w = s; w.lock() | Observe without owning; lock() returns a shared_ptr or an empty one |
p.get() p.reset() *p p->x | Get raw pointer / release / dereference |
s.use_count() | Number of owners of a shared_ptr |
std::unique_ptr<FILE, decltype(&fclose)> f(fopen("x", "r"), &fclose); | Custom deleter for C resources |
std::lock_guard<std::mutex> lock(m); | RAII lock: unlocks automatically |
Templates, lambdas & modern features
template <typename T> T f(T a); | Function template |
template <typename... Args> auto f(Args... a) { return (a + ...); } | Variadic template with fold expression |
template <std::integral T> T f(T x); | Concept constrains the type (C++20) |
[x, &y](int a) { return a + x; } | Lambda: x captured by copy, y by reference |
[=] [&] [this] | Capture everything by copy / everything by reference / the object |
std::optional<int> f(); return std::nullopt; | Optional value |
std::variant<int, std::string> v; std::visit(f, v); | Type-safe union |
v | std::views::filter(p) | std::views::transform(f) | Ranges pipeline (lazy, C++20) |
if constexpr (std::is_integral_v<T>) { } | Branching at compile time |
Files & errors
std::ifstream in("datei.txt"); if (!in) { } | Open a file for reading and check it |
std::ofstream out("datei.txt", std::ios::app); | File for writing (app = append) |
while (std::getline(in, zeile)) { } | Read line by line |
try { ... } catch (const std::exception& e) { e.what(); } | Catch exceptions (always by const&) |
throw std::runtime_error("Text"); | Raise an error |
void f() noexcept; | Function is guaranteed not to throw |
namespace fs = std::filesystem; fs::exists(p) | File system: paths, existence, directories (C++17) |
Compiler flags & tools
g++ -std=c++20 main.cpp -o prog | Compile with C++20 |
-Wall -Wextra -Wpedantic | Enable important warnings (always!) |
-O2 -O0 -g | Optimize for release / no optimization with debug info |
-fsanitize=address,undefined | Find memory errors and UB at runtime |
-pthread | Link in threads |
g++ -c a.cpp && g++ a.o b.o -o prog | Compile and link separately |
cmake -S . -B build && cmake --build build | Configure and build a project with CMake |
gdb ./prog lldb ./prog | Start the debugger |