C++ Cheat Sheet
Program structure, operators, formatting, strings, loops, functions, recursion, vectors, pointers, classes, STL algorithms, exceptions, files, smart pointers, move semantics, templates and threads on one printable page.
Program structure
| Syntax | What it does | Lesson |
|---|---|---|
#include <iostream> | Use cout and cin | Introduction |
int main() { return 0; } | Program entry point | Introduction |
cout << "Hi" << endl; | Print a line | Introduction |
g++ app.cpp -o app | Compile | Introduction |
Variables & strings
| Syntax | What it does | Lesson |
|---|---|---|
int double char bool | Core types | Variables |
const double PI = 3.14; auto x = 5; | Constant / inferred type | Variables |
cin >> x; getline(cin, s); | Read a value / a line | Variables |
s.size() s.substr(p, n) | Length, part of a string | Strings |
s.find("x") != string::npos | Search inside text | Strings |
stoi(s) stod(s) to_string(n) | Convert text and numbers | Strings |
Conditions & loops
Functions, vectors & structs
| Syntax | What it does | Lesson |
|---|---|---|
int sq(int n) { return n * n; } | Function | Functions |
void f(int& x) void f(const T& x) | Reference / read-only | Functions |
vector<int> v = {1, 2}; v.push_back(3); | Resizable list | Vectors |
for (const auto& x : v) { } | Visit every item | Vectors |
struct P { string name; int age; }; | Group data | Structs |
enum class Size { S, M, L }; | Named options | Structs |
Pointers & classes
| Syntax | What it does | Lesson |
|---|---|---|
int* p = &x; *p = 5; | Pointer, dereference | Pointers |
nullptr p->member | Null pointer, member access | Pointers |
class A { private: ... public: ... }; | Class with access control | Classes |
A(int x) : x(x) {} | Constructor with initializer list | Classes |
int get() const; | Function that doesn't change the object | Classes |
class B : public A virtual override | Inheritance and polymorphism | Inheritance |
STL & files
| Syntax | What it does | Lesson |
|---|---|---|
map<string, int> m; m["k"] = 1; | Key-value pairs | Maps & sets |
for (const auto& [k, v] : m) | Loop over a map | Maps & sets |
set<int> s; s.insert(3); | Unique values | Maps & sets |
sort(v.begin(), v.end()); | Sort a range | Maps & sets |
ofstream out("f.txt"); ifstream in("f.txt"); | Write / read files | Files |
while (getline(in, line)) { } | Read line by line | Files |
Memory & templates
| Syntax | What it does | Lesson |
|---|---|---|
auto p = make_unique<T>(args); | Single owner on the heap | Smart pointers |
auto q = move(p); | Transfer ownership | Smart pointers |
auto s = make_shared<T>(args); | Shared ownership | Smart pointers |
template <typename T> T f(T a); | Function template | Templates |
template <typename T> class Box { }; | Class template | Templates |
Operators, formatting & recursion
| Syntax | What it does | Lesson |
|---|---|---|
7 / 2 7 % 2 static_cast<double>(a) / b | Integer division, remainder, decimal division | Operators & Math |
sqrt(x) pow(b, e) round(x) ceil(x) | cmath functions | Operators & Math |
cout << fixed << setprecision(2) << x; | Two decimal places | Formatting & Streams |
cout << setw(10) << left << s; | Column width and alignment | Formatting & Streams |
ostringstream out; out << x; out.str(); | Build a string | Formatting & Streams |
getline(in, piece, ',') | Split text on a character | Formatting & Streams |
if (n <= 1) return 1; return n * f(n - 1); | Base case and recursive case | Recursion |
Algorithms, lambdas & exceptions
| Syntax | What it does | Lesson |
|---|---|---|
[](int x) { return x > 0; } | A lambda | Algorithms & Lambdas |
sort(v.begin(), v.end(), cmp) | Sort with a comparison | Algorithms & Lambdas |
find_if count_if any_of | Search and count by a rule | Algorithms & Lambdas |
accumulate(v.begin(), v.end(), 0) | Sum a range | Algorithms & Lambdas |
v.erase(remove_if(...), v.end()) | Remove matching items | Algorithms & Lambdas |
throw runtime_error("msg"); | Signal an error | Exceptions |
try { } catch (const exception& e) { e.what(); } | Handle an error | Exceptions |
Advanced C++
| Syntax | What it does | Lesson |
|---|---|---|
T operator+(const T& o) const; | Overload an operator | Operator Overloading |
ostream& operator<<(ostream& out, const T& t) | Print your type | Operator Overloading |
#pragma once | Header protection | Headers, Files & CMake |
g++ -std=c++17 main.cpp geo.cpp -o app | Build several files | Headers, Files & CMake |
T b = std::move(a); | Move instead of copy | Move Semantics |
v.emplace_back(args...) | Build in place | Move Semantics |
optional<T> value_or(x) nullopt | Maybe a value | optional & variant |
variant<A, B> visit(f, v) | One of several types | optional & variant |
thread t(f); t.join(); | Run code in parallel | Threads & Concurrency |
lock_guard<mutex> lock(m); atomic<int> | Protect shared data | Threads & Concurrency |
auto f = async(launch::async, g); f.get(); | Background result | Threads & Concurrency |
How to use this C++ cheat sheet
This C++ cheat sheet gathers the syntax you'll look up most, in the same order as the course: program structure, variables and input, strings, conditions and loops, functions, vectors, recursion, formatting, structs and enums, pointers, classes and inheritance, the STL and algorithms, exceptions, files, operator overloading, project structure, smart pointers, move semantics, templates, optional, variant and threads. Every row links to the lesson that explains it properly, with examples and common mistakes.
Keep it next to your editor while you practise with g++, clang or Visual Studio. When you can't remember whether find returns npos or -1, how to open a file for appending, or the shape of a class with a constructor initializer list, a quick look answers it. Type a keyword into the filter box to jump straight to the right row, or print the page as a one-sheet reference.
C++ gotchas worth remembering
- Uninitialised variables hold garbage.
int total;can contain any value. Always initialise, for exampleint total = 0;orint total{};. - = is not ==.
if (x = 5)assigns and is always true. Turn on compiler warnings (-Wall -Wextra) to catch it. - Integer division truncates.
5 / 2is2. Use5.0 / 2orstatic_cast<double>when you need decimals. - Out-of-range access isn't checked.
v[10]on a 5-element vector is undefined behaviour. Usev.at(10)while learning, because it throws a clear exception. - Pass big objects by const reference.
void print(const std::string& s)avoids copying the whole string on every call. - Prefer smart pointers to new and delete.
std::make_uniquefrees memory automatically, so you can't forget adeleteor call it twice.
Keep the sheet next to your compiler and check each snippet with the C++ quiz when you finish a section.
The C++ lessons behind this cheat sheet
Beginner
Intermediate
Advanced
Language and standard library
- 26C++ Scope, Namespaces and Linkage
- 27C++ Const Correctness and Interfaces
- 28C++ Casts and Numeric Safety
- 29C++ Array, Span and Multidimensional Data
- 30C++ String View Lifetimes
- 31C++ Iterator and Reference Invalidation
- 32C++ List and Deque Container Choices
- 33C++ Stack, Queue and Priority Queue
- 34C++ Unordered Containers and Hashing
- 35C++ Chrono Clocks, Durations and Dates
- 36C++ Random Engines and Distributions
- 37C++ Friend Functions and Access Design
- 38C++ Multiple Inheritance and Virtual Bases
- 39C++ Special Members and Exception Guarantees