Skip to content
Tutorials Center
My learning

Topics

Lesson 162 of 171 ยท Practice and Review

C++ Cheat Sheet

A one-page modern C++ cheat sheet with types, strings, format specs, control flow, functions, lambdas, smart pointers, classes, templates, STL containers and ranges.

This page squeezes the whole C++ course into one dense reference: the syntax, types, standard library pieces and idioms you reach for every day, in compact snippets you can scan in seconds. Keep it open while you work through the practice exercises, while you write your own programs, or the evening before an interview.

Everything here is modern C++ (C++17, C++20 and C++23, compiled with GCC 15 in our editors). Each section links to the lesson that explains the topic properly, with the reasons behind the rules. The items that trip people up most often come with live editors, so you can run them and watch the behavior yourself.

Program basics

Skeleton, output and input

C++
#include <print>      // std::print, std::println (C++23)
#include <iostream>   // std::cin, std::cout, std::cerr
#include <string>

int main() {
    std::println("Hello, {}!", "world");     // newline added
    std::print("x = {}, y = {}\n", 3, 4.5);  // no newline added
    std::cout << "classic " << 42 << '\n';   // '\n' is cheaper than std::endl
    std::println(stderr, "errors go to stderr");

    int age{};
    std::string word, line;
    std::cin >> age >> word;          // reads whitespace-separated tokens
    std::cin >> std::ws;              // skip the leftover newline before getline
    std::getline(std::cin, line);     // reads the rest of a line
    if (!std::cin) { /* input failed or hit end of file */ }
    return 0;                         // optional in main
}

Build outside our editor with g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app. See Getting Started, Printing Output, Reading User Input and How C++ Works.

Fundamental types

Type Typical size Example literals
bool 1 byte true, false
char 1 byte 'A', '\n'
int 4 bytes 42, 0x2A, 0b101010, 1'000'000
long long 8 bytes 42LL, 9'000'000'000
unsigned 4 bytes 42u
std::size_t 8 bytes (64-bit) v.size(), 42uz (C++23)
float 4 bytes 3.14f
double 8 bytes 3.14, 1e-9
std::int32_t, std::uint8_t, โ€ฆ exact from <cstdint>

Sizes other than char are implementation-defined; check with sizeof(T) and std::numeric_limits<T>::max() from <limits>. See Fundamental Data Types, Integer Types and Floating-Point Numbers.

Variables, constants and auto

C++
int a = 5;              // copy initialization
int b(5);               // direct initialization
int c{5};               // brace initialization: rejects narrowing
int d{};                // value-initialized to 0
int e;                  // UNINITIALIZED inside a function: reading it is UB
// int f{3.7};          // error: narrowing double -> int

const int max_users = 100;          // can't change after initialization
constexpr double tax = 0.21;        // known at compile time
constexpr int square(int x) { return x * x; }  // usable at compile time
consteval int must_be_compile_time(int x) { return x + 1; }

auto n = 42;            // int
auto s = std::string{"hi"};
const auto& ref = s;    // auto drops const and & unless you write them
decltype(n) m = 0;      // "same type as n"
using Score = std::uint32_t;  // type alias (prefer over typedef)

See Variables, Type Deduction with auto, Constants and Type Aliases.

Operators and casts

C++
7 / 2        // 3     integer division truncates toward zero
-7 / 2       // -3
-7 % 2       // -1    remainder takes the sign of the left operand
7.0 / 2      // 3.5
x += 2; x++; ++x;            // ++x is never slower than x++
a == b; a != b; a <=> b;     // three-way comparison (C++20)
a && b; a || b; !a;          // short-circuit
flags & mask; flags | bit; x ^ y; ~x; x << 3; x >> 1;
cond ? yes : no;

static_cast<double>(total) / count;  // the cast you use 99% of the time
// (double)total                     // C-style cast: avoid, it can do anything
std::to_underlying(Color::red);      // enum class -> integer (C++23)

See Arithmetic Operators, Comparison and Logical Operators, Bitwise Operators, Operator Precedence and Type Conversions and Casts.

Strings

std::string and std::string_view

C++
std::string s = "Hello, World";
s.size();  s.empty();  s[0];  s.at(0);   // at() throws std::out_of_range
s += "!";  s.append("??");  s.push_back('.');
s.substr(7, 5);              // "World" (start, count)
s.find("o");                 // 4, or std::string::npos if missing
s.rfind('o');  s.find('o', 5);
s.replace(0, 5, "Howdy");    // (start, count, new text)
s.insert(0, ">> ");  s.erase(0, 3);
s.starts_with("He");  s.ends_with('!');  s.contains("lo");  // C++20 / C++23
s.c_str();                   // const char* for C APIs
std::string(3, '*');         // "***"
for (char ch : s) { /* ... */ }

std::string_view view = s;   // non-owning, cheap to copy
view.substr(0, 5);           // no allocation
void greet(std::string_view name);   // best read-only string parameter
// Never return a string_view into a local or temporary string: it dangles.

Conversions: std::to_string(42), std::stoi("42") and std::stod("2.5") (both throw on bad input), or std::from_chars for fast, exception-free parsing. See Strings, String Methods, std::string_view and Converting Between Strings and Numbers.

Format specs

The spec goes after a colon: {:[[fill]align][sign][#][0][width][.precision][type]}.

Spec Example Result
width, right-align std::format("[{:>6}]", 42) [ 42]
left, center "[{:<6}]", "[{:^6}]" with "ab" [ab ], [ ab ]
fill "{:*^7}" with "ab" **ab***
zero pad "{:05}" with 42 00042
precision "{:.2f}" with 3.14159 3.14
sign "{:+}" with 5 +5
hex, binary "{:#x}", "{:08b}" with 255, 5 0xff, 00000101
positional "{1} {0}" with "a", "b" b a
ranges (C++23) "{}" with std::vector{1, 2} [1, 2]
C++ Format specs in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

See Formatting with std::format and std::print.

Control flow

C++
if (x > 0) { /*...*/ } else if (x < 0) { /*...*/ } else { /*...*/ }
if (auto it = m.find(key); it != m.end()) { use(it->second); }  // if with initializer

switch (cmd) {
    case 'a': add(); break;
    case 'q': [[fallthrough]];
    case 'x': quit(); break;
    default: help();
}

for (int i = 0; i < n; ++i) { }
for (const auto& item : items) { }           // read without copying
for (auto& item : items) { item *= 2; }      // modify in place
for (auto [key, value] : my_map) { }         // structured bindings
while (std::cin >> x) { }                    // loop until input ends
do { /* at least once */ } while (again);
break;  continue;                            // nearest loop only

See if, else if and else, switch Statements, while Loops, for Loops and break, continue and goto.

Functions

Parameter Copies? Can modify caller's object? Use for
T value yes no small types (int, double, string_view), or when you need a copy anyway
const T& value no no large read-only inputs (std::string, std::vector)
T& value no yes in-out parameters
T&& value no moves from it "sink" overloads, perfect forwarding
std::span<const T> no no any contiguous sequence (array, vector)
C++
int add(int a, int b);                         // declaration (prototype)
int add(int a, int b) { return a + b; }        // definition
void log(std::string_view msg, int level = 1); // default arguments go last
double area(double r);  double area(double w, double h);  // overloading
auto divide(int a, int b) -> double;           // trailing return type

std::pair<int, int> min_max(const std::vector<int>& v);
auto [lo, hi] = min_max(values);               // structured bindings
std::optional<int> find_id(std::string_view name);  // "maybe a value"
std::expected<int, std::string> parse(std::string_view text);  // value or error (C++23)
[[nodiscard]] int compute();                   // warn if the result is ignored
// Never return a reference or pointer to a local variable.

See Functions, Parameters, Default Arguments, Returning Values, Function Overloading and Recursion.

Lambdas

Capture Meaning
[] nothing
[x], [=] copy x / everything used
[&x], [&] reference to x / everything used (watch lifetimes)
[this], [*this] the object by pointer / by copy
[n = std::move(v)] init capture: a new member initialized from an expression
C++
auto square = [](int x) { return x * x; };
auto counter = [count = 0]() mutable { return ++count; };  // mutable: change copies
auto print_any = [](const auto& value) { std::println("{}", value); };  // generic
std::ranges::sort(people, [](const Person& a, const Person& b) { return a.age < b.age; });
const auto config = [&] { Config c; c.load(); return c; }();  // immediately invoked
std::function<int(int)> f = square;            // type-erased callable (has a cost)

See Lambda Expressions, Function Objects and std::function and Function Pointers.

Pointers, references and memory

C++
int x = 10;
int& ref = x;            // alias: must be bound at creation, can't be reseated
int* ptr = &x;           // address of x
*ptr = 20;               // x is now 20
int* nothing = nullptr;  // never dereference
const int* p1 = &x;      // pointer to const: *p1 = 1 is an error
int* const p2 = &x;      // const pointer: p2 = other is an error
// Read declarations right to left: "p2 is a const pointer to int".
Tool Owns? Copyable? Use for
T object / std::vector<T> yes yes the default: values and containers
std::unique_ptr<T> yes, alone no (move only) single owner, polymorphic objects, pimpl
std::shared_ptr<T> yes, shared yes (ref count) genuinely shared lifetime
std::weak_ptr<T> no yes observing a shared_ptr, breaking cycles
T*, T& no yes non-owning access to something that outlives you
new / delete manual n/a avoid in application code
C++ Smart pointers and ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

See References, Pointers, const with Pointers, Dynamic Memory, std::unique_ptr, shared_ptr and weak_ptr and Undefined Behavior.

Classes

C++
class Account {
public:
    explicit Account(std::string owner, double balance = 0)
        : owner_(std::move(owner)), balance_(balance) {}   // member initializer list

    void deposit(double amount) {
        if (amount <= 0) { throw std::invalid_argument("amount must be positive"); }
        balance_ += amount;
    }
    double balance() const { return balance_; }            // const: doesn't modify
    static int count() { return count_; }

private:
    std::string owner_;
    double balance_ = 0;               // default member initializer
    inline static int count_ = 0;      // one per class, not per object
};

struct Point {                         // struct = class with public default access
    int x = 0, y = 0;
    auto operator<=>(const Point&) const = default;   // also gives ==, <, >, ...
};
Point p{.x = 1, .y = 2};               // designated initializers (C++20)

Inheritance and polymorphism

C++
class Shape {
public:
    virtual ~Shape() = default;              // a polymorphic base needs a virtual destructor
    virtual double area() const = 0;         // pure virtual: Shape is abstract
};

class Circle final : public Shape {
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return std::numbers::pi * r_ * r_; }
private:
    double r_;
};

std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
for (const auto& s : shapes) { std::println("{:.2f}", s->area()); }
// Copying a Circle into a plain Shape variable "slices" it: use pointers or references.

Special member functions

Rule What it says
Rule of zero Let members (std::string, std::vector, std::unique_ptr) manage resources and write none of the five.
Rule of three If you write a destructor, copy constructor or copy assignment, you probably need all three.
Rule of five Add the move constructor and move assignment (mark them noexcept).
= default / = delete Ask for the compiler's version / forbid the operation.

See Classes and Objects, Constructors, Destructors and RAII, Operator Overloading, Move Semantics, The Rule of Zero, Three and Five, Inheritance and Virtual Functions.

Enums, structs and variants

C++
enum class Color : std::uint8_t { red, green, blue };  // scoped: Color::red
auto c = Color::green;
switch (c) { case Color::red: /*...*/ break; default: break; }

std::variant<int, std::string> v = "text";              // a type-safe union
std::visit([](const auto& value) { std::println("{}", value); }, v);
std::optional<int> maybe;  maybe.value_or(0);  if (maybe) { *maybe; }

See Enumerations, Structs, Aggregates and Unions and optional, variant, any and expected.

Templates and concepts

C++
template <typename T>
T biggest(T a, T b) { return a < b ? b : a; }       // biggest(3, 7), biggest<double>(3, 7.5)

auto twice(auto x) { return x + x; }                // abbreviated template (C++20)

template <typename T, std::size_t N>
class RingBuffer { std::array<T, N> data_{}; };    // type and non-type parameters
RingBuffer<int, 16> buffer;

template <std::integral T>                           // constrained with a concept
T gcd_of(T a, T b) { return b == 0 ? a : gcd_of(b, a % b); }

template <typename T>
concept Printable = requires(std::ostream& os, T value) { os << value; };

template <typename... Args>
auto sum(Args... args) { return (args + ... + 0); } // fold expression

if constexpr (std::is_floating_point_v<T>) { /* compiled only for floats */ }
static_assert(sizeof(int) >= 4, "need 32-bit int");

See Function Templates, Class Templates, Concepts, Variadic Templates, Compile-Time Programming and Type Traits.

STL containers

Container Ordered? Lookup Insert / erase Notes
std::vector<T> by position O(1) index O(1) amortized at end, O(n) middle the default choice
std::array<T, N> by position O(1) index fixed size lives on the stack
std::deque<T> by position O(1) index O(1) at both ends
std::list<T> by position O(n) O(1) with an iterator stable iterators, slow to walk
std::map<K, V> sorted keys O(log n) O(log n) red-black tree
std::unordered_map<K, V> no O(1) average O(1) average hash table
std::set<T> / std::unordered_set<T> sorted / no O(log n) / O(1) avg same unique keys
std::stack, std::queue adapters top / front O(1) wrap a deque by default
std::priority_queue<T> heap O(1) top O(log n) max-heap by default
C++
std::vector<int> v{3, 1, 4};
v.push_back(1);  v.emplace_back(5);  v.pop_back();
v.reserve(100);  v.size();  v.capacity();  v.front();  v.back();
v.insert(v.begin() + 1, 9);  v.erase(v.begin());
std::erase(v, 4);  std::erase_if(v, [](int x) { return x > 3; });  // C++20

std::map<std::string, int> ages{{"Ana", 31}};
ages["Ben"] = 25;              // operator[] INSERTS a default value if the key is missing
ages.try_emplace("Cy", 40);    // inserts only if absent
ages.contains("Ana");          // C++20
if (auto it = ages.find("Dee"); it != ages.end()) { /*...*/ }
for (const auto& [name, age] : ages) { }   // in key order

std::priority_queue<int, std::vector<int>, std::greater<>> min_heap;  // smallest on top

See The Standard Template Library, std::vector, std::array, std::map, std::unordered_map, std::set, Container Adapters and Iterators.

Algorithms and ranges

C++
#include <algorithm>   // sort, find, count, ...
#include <numeric>     // accumulate, iota, reduce, ...
#include <ranges>      // views

std::ranges::sort(v);                         // ascending
std::ranges::sort(v, std::greater{});         // descending
std::ranges::sort(people, {}, &Person::age);  // by a member ("projection")
std::ranges::find(v, 42);                     // iterator, or v.end()
std::ranges::count_if(v, is_even);
std::ranges::max_element(v);  std::ranges::minmax(v);
std::ranges::binary_search(sorted, 7);        // needs sorted input
std::ranges::reverse(v);  std::ranges::unique(v);  std::ranges::fill(v, 0);
std::ranges::any_of(v, pred);  std::ranges::all_of(v, pred);
std::accumulate(v.begin(), v.end(), 0);       // sum; use 0.0 for doubles!
std::iota(v.begin(), v.end(), 1);             // 1, 2, 3, ...

auto evens_squared = v | std::views::filter(is_even)
                       | std::views::transform([](int x) { return x * x; });
auto result = evens_squared | std::ranges::to<std::vector>();   // C++23
C++ A ranges pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

See Algorithms: Searching, Sorting and Counting, Algorithms: Transforming and Modifying, Numeric Algorithms and Ranges and Views.

Errors

C++
try {
    auto n = std::stoi(text);
    if (n < 0) { throw std::out_of_range("negative"); }
} catch (const std::invalid_argument& e) {    // catch by const reference
    std::println("not a number: {}", e.what());
} catch (const std::exception& e) {           // base class last
    std::println("error: {}", e.what());
}

class ConfigError : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;   // inherit the constructors
};

void swap_fast(Buffer& other) noexcept;        // promises not to throw
assert(index < size);                          // <cassert>, removed with -DNDEBUG
Approach Use when
exceptions errors are rare and must not be ignored; constructors that can fail
std::optional<T> "no result" is normal and needs no explanation
std::expected<T, E> (C++23) the caller should handle the failure and know why
assert / static_assert catching programmer mistakes during development / at compile time

See Exceptions, Custom Exception Classes, Exception Safety and noexcept, Error Handling Without Exceptions and Assertions and Debugging.

Files and streams

C++
#include <fstream>
#include <sstream>
#include <filesystem>
namespace fs = std::filesystem;

std::ofstream out("notes.txt");               // std::ios::app to append
out << "line one\n";
std::ifstream in("notes.txt");
if (!in) { /* could not open */ }
for (std::string line; std::getline(in, line); ) { }
// Files close automatically when the stream object is destroyed (RAII).

std::istringstream parts("10 20 30");
int total = 0;
for (int n; parts >> n; ) { total += n; }

fs::exists("notes.txt");  fs::file_size("notes.txt");
fs::create_directories("out/logs");
for (const auto& entry : fs::directory_iterator(".")) { entry.path().filename(); }

See I/O Streams in Depth, Reading and Writing Text Files, String Streams and The Filesystem Library.

Utilities and concurrency

C++
using namespace std::chrono_literals;
auto start = std::chrono::steady_clock::now();
auto elapsed = std::chrono::steady_clock::now() - start;
std::println("{}", std::chrono::duration_cast<std::chrono::milliseconds>(elapsed));

std::mt19937 gen{std::random_device{}()};
std::uniform_int_distribution<int> dice{1, 6};
int roll = dice(gen);

std::jthread worker([](std::stop_token st) { while (!st.stop_requested()) { /*...*/ } });
std::mutex m;
{ std::scoped_lock lock(m); /* one thread at a time */ }
std::atomic<int> hits{0};  hits.fetch_add(1);  hits++;
auto future = std::async(std::launch::async, [] { return 42; });
int answer = future.get();                     // waits; rethrows the task's exception

See chrono, Random Numbers, Threads, Mutexes and Locks, Atomics and std::async, Futures and Promises.

Gotchas worth remembering

  • Comparing signed and unsigned values converts the signed one: -1 < 1u is false.
  • std::accumulate(v.begin(), v.end(), 0) sums doubles as int. Start with 0.0.
  • map[key] inserts a default value when the key is missing, even if you only meant to read it.
  • Signed integer overflow, out-of-bounds indexing and use-after-free are undefined behavior: the program may seem to work, then fail elsewhere.
  • Adding to a std::vector can reallocate and invalidate every iterator, pointer and reference into it.
  • std::vector<bool> packs bits and doesn't hold real bool objects; auto& b = flags[0] doesn't compile.
  • A base class without a virtual destructor leaks or corrupts when you delete a derived object through a base pointer.
C++ Gotchas you can run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first line prints true because the cast to int keeps the comparison signed; the second shows what happens when -1 becomes an unsigned number (4294967295). The accumulate call with 0 truncates every partial sum to int, so it prints 6 instead of 7.5. See Best Practices and Common Mistakes for more of these.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does std::println("{:>5}|{:<5}|", 42, 7); print?

    5 right-aligns 42 in a field of 5 characters (three spaces first), and <5 left-aligns 7 with four spaces after it.

  2. 2. You call ages["Zed"] on a std::map that has no key "Zed". What happens?

    operator[] always returns a reference to an element, so it creates one when the key is missing. Use find(), contains() or at() to read without inserting.
  3. 3. Which smart pointer fits an object that has exactly one owner at a time?

    unique_ptr expresses exclusive ownership at zero overhead and can be moved to transfer it. shared_ptr adds reference counting you don't need.
  4. 4. What is the value of -7 / 2 and -7 % 2 in C++?

    Integer division truncates toward zero, giving -3, and the remainder takes the sign of the left operand, so (-3 * 2) + (-1) == -7.

Summary

  • Print with std::println and format specs; read with std::cin >> and std::getline, and check that input succeeded.
  • Initialize everything, prefer brace initialization, and use const/constexpr for values that don't change.
  • Pass large read-only inputs by const& (or std::string_view/std::span), return results by value, and use std::optional or std::expected for results that may be missing.
  • Own memory through values, containers and std::unique_ptr; reach for std::shared_ptr only for truly shared lifetime.
  • Default to std::vector, use maps and sets for lookups, and let algorithms and ranges do the looping.
  • Remember the classic traps: signed/unsigned comparison, map[] inserting, iterator invalidation and undefined behavior.

Next: C++ Programs: 40 Classic Examples, where you'll see these tools at work in short, complete programs.