C++Printable

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.

Back to the C++ tutorial

Program structure

SyntaxWhat it doesLesson
#include <iostream>Use cout and cinIntroduction
int main() { return 0; }Program entry pointIntroduction
cout << "Hi" << endl;Print a lineIntroduction
g++ app.cpp -o appCompileIntroduction

Variables & strings

SyntaxWhat it doesLesson
int double char boolCore typesVariables
const double PI = 3.14; auto x = 5;Constant / inferred typeVariables
cin >> x; getline(cin, s);Read a value / a lineVariables
s.size() s.substr(p, n)Length, part of a stringStrings
s.find("x") != string::nposSearch inside textStrings
stoi(s) stod(s) to_string(n)Convert text and numbersStrings

Conditions & loops

SyntaxWhat it doesLesson
if (c) { } else if (d) { } else { }Branchingif/else
switch (n) { case 1: ...; break; }Match int or charif/else
for (int i = 0; i < n; i++) { }Counted loopLoops
while (c) { } do { } while (c);Condition loopsLoops

Functions, vectors & structs

SyntaxWhat it doesLesson
int sq(int n) { return n * n; }FunctionFunctions
void f(int& x) void f(const T& x)Reference / read-onlyFunctions
vector<int> v = {1, 2}; v.push_back(3);Resizable listVectors
for (const auto& x : v) { }Visit every itemVectors
struct P { string name; int age; };Group dataStructs
enum class Size { S, M, L };Named optionsStructs

Pointers & classes

SyntaxWhat it doesLesson
int* p = &x; *p = 5;Pointer, dereferencePointers
nullptr p->memberNull pointer, member accessPointers
class A { private: ... public: ... };Class with access controlClasses
A(int x) : x(x) {}Constructor with initializer listClasses
int get() const;Function that doesn't change the objectClasses
class B : public A virtual overrideInheritance and polymorphismInheritance

STL & files

SyntaxWhat it doesLesson
map<string, int> m; m["k"] = 1;Key-value pairsMaps & sets
for (const auto& [k, v] : m)Loop over a mapMaps & sets
set<int> s; s.insert(3);Unique valuesMaps & sets
sort(v.begin(), v.end());Sort a rangeMaps & sets
ofstream out("f.txt"); ifstream in("f.txt");Write / read filesFiles
while (getline(in, line)) { }Read line by lineFiles

Memory & templates

SyntaxWhat it doesLesson
auto p = make_unique<T>(args);Single owner on the heapSmart pointers
auto q = move(p);Transfer ownershipSmart pointers
auto s = make_shared<T>(args);Shared ownershipSmart pointers
template <typename T> T f(T a);Function templateTemplates
template <typename T> class Box { };Class templateTemplates

Operators, formatting & recursion

SyntaxWhat it doesLesson
7 / 2 7 % 2 static_cast<double>(a) / bInteger division, remainder, decimal divisionOperators & Math
sqrt(x) pow(b, e) round(x) ceil(x)cmath functionsOperators & Math
cout << fixed << setprecision(2) << x;Two decimal placesFormatting & Streams
cout << setw(10) << left << s;Column width and alignmentFormatting & Streams
ostringstream out; out << x; out.str();Build a stringFormatting & Streams
getline(in, piece, ',')Split text on a characterFormatting & Streams
if (n <= 1) return 1; return n * f(n - 1);Base case and recursive caseRecursion

Algorithms, lambdas & exceptions

SyntaxWhat it doesLesson
[](int x) { return x > 0; }A lambdaAlgorithms & Lambdas
sort(v.begin(), v.end(), cmp)Sort with a comparisonAlgorithms & Lambdas
find_if count_if any_ofSearch and count by a ruleAlgorithms & Lambdas
accumulate(v.begin(), v.end(), 0)Sum a rangeAlgorithms & Lambdas
v.erase(remove_if(...), v.end())Remove matching itemsAlgorithms & Lambdas
throw runtime_error("msg");Signal an errorExceptions
try { } catch (const exception& e) { e.what(); }Handle an errorExceptions

Advanced C++

SyntaxWhat it doesLesson
T operator+(const T& o) const;Overload an operatorOperator Overloading
ostream& operator<<(ostream& out, const T& t)Print your typeOperator Overloading
#pragma onceHeader protectionHeaders, Files & CMake
g++ -std=c++17 main.cpp geo.cpp -o appBuild several filesHeaders, Files & CMake
T b = std::move(a);Move instead of copyMove Semantics
v.emplace_back(args...)Build in placeMove Semantics
optional<T> value_or(x) nulloptMaybe a valueoptional & variant
variant<A, B> visit(f, v)One of several typesoptional & variant
thread t(f); t.join();Run code in parallelThreads & Concurrency
lock_guard<mutex> lock(m); atomic<int>Protect shared dataThreads & Concurrency
auto f = async(launch::async, g); f.get();Background resultThreads & 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 example int total = 0; or int total{};.
  • = is not ==. if (x = 5) assigns and is always true. Turn on compiler warnings (-Wall -Wextra) to catch it.
  • Integer division truncates. 5 / 2 is 2. Use 5.0 / 2 or static_cast<double> when you need decimals.
  • Out-of-range access isn't checked. v[10] on a 5-element vector is undefined behaviour. Use v.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_unique frees memory automatically, so you can't forget a delete or 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