Cheatsheets / C++

C++ Cheatsheet

Complete C++ reference. Hit Ctrl+P to print.

Basics

#include <iostream>Include standard I/O header
using namespace std;Use standard namespace (avoid in headers)
int main() { return 0; }Entry point - return 0 means success
std::cout << "Hello" << std::endl;Print to stdout
std::cin >> x;Read from stdin
// single line commentSingle-line comment
/* multi line */Multi-line comment
int x = 5; double d = 3.14; bool b = true; char c = 'A';Common types
auto x = 42;auto - infer type from initializer
const int MAX = 100;Compile-time constant
constexpr int SQ = 10 * 10;constexpr - evaluated at compile time
int x {5};Brace initialization - prevents narrowing
nullptrNull pointer constant (use instead of NULL)
sizeof(int)Size in bytes of type or variable
static_cast<double>(x)Safe explicit cast

Pointers & References

int* p = &x;Pointer to int, initialized to address of x
*pDereference pointer - access value
p->memberAccess member via pointer (same as (*p).member)
int& ref = x;Reference - alias for x, cannot be rebound
void swap(int& a, int& b)Pass by reference - modifies caller variable
const int& r = x;Const reference - read-only alias
int arr[5] = {1, 2, 3, 4, 5};Stack-allocated array
int* p = new int(42);Heap allocation
delete p; p = nullptr;Free heap memory - set to nullptr after
int* arr = new int[10];Heap array
delete[] arr;Free heap array
int** pp = &p;Pointer to pointer
int& arr[5](invalid) - prefer std::array or span

Smart Pointers

#include <memory>Required header for smart pointers
auto p = std::make_unique<int>(42);unique_ptr - sole owner, auto-deleted
auto p = std::make_shared<User>("Alice");shared_ptr - reference-counted shared ownership
std::weak_ptr<User> wp = sp;weak_ptr - non-owning reference to shared_ptr
if (auto locked = wp.lock()) { }Lock weak_ptr to get shared_ptr (check for null)
p.get()Get raw pointer (do not delete it)
p.reset()Release ownership - destroys managed object
std::move(p)Transfer unique_ptr ownership

Control Flow

if (x > 0) { } else if (x < 0) { } else { }if / else if / else
switch (x) { case 1: break; default: break; }switch - fallthrough unless break
for (int i = 0; i < n; i++) { }C-style for loop
for (auto& item : vec) { }Range-based for - iterate over container
for (const auto& [key, val] : map) { }Structured bindings in range-for (C++17)
while (x > 0) { }while loop
do { } while (x > 0);do-while loop
break / continueExit loop / skip to next iteration
[[likely]] / [[unlikely]]Branch prediction hints (C++20)

Functions

int add(int a, int b) { return a + b; }Function definition
int add(int a, int b = 0)Default argument (rightmost only)
void swap(int& a, int& b)Pass by reference
int process(const std::string& s)Pass by const reference - efficient, read-only
auto add(int a, int b) -> intTrailing return type
inline int sq(int x) { return x * x; }Inline - suggest inlining at call sites
template<typename T> T max(T a, T b)Function template
template<typename T, typename U>Multiple template parameters
auto fn = [](int x) { return x * 2; };Lambda expression
[&](int x) { return x + y; }Lambda capturing by reference
[=](int x) { return x + y; }Lambda capturing by value
[x, &y](int z) { }Lambda capturing specific variables
std::function<int(int)> fnStore any callable with signature int(int)
[[nodiscard]] int parse()Warn if return value is discarded

Classes & OOP

class User { public: std::string name; };Class - members private by default
struct Point { int x; int y; };Struct - members public by default
User(std::string n) : name(std::move(n)) {}Constructor with member initializer list
~User() { }Destructor - called on object destruction
User(const User& other)Copy constructor
User(User&& other) noexceptMove constructor
User& operator=(const User& other)Copy assignment operator
User& operator=(User&& other) noexceptMove assignment operator
= default; / = delete;Use compiler-generated / disable special member
class Admin : public User { };Public inheritance
virtual void speak() { }Virtual method - overridable in derived class
virtual void speak() = 0;Pure virtual - abstract class
void speak() override { }Override virtual method - override keyword prevents mistakes
void speak() final { }final - cannot be further overridden
template<typename T> class Box { T value; };Class template
friend class Admin;Grant another class access to private members

STL Containers

std::vector<int> v = {1, 2, 3};Dynamic array
v.push_back(4); v.emplace_back(5);Append element
v.pop_back();Remove last element
v[i] / v.at(i)Access element - at() bounds-checks
v.size() / v.empty()Size and empty check
v.reserve(100);Pre-allocate capacity
std::array<int, 5> arr = {1,2,3,4,5};Fixed-size array with STL interface
std::string s = "hello";Dynamic string
s += " world"; s.append("!");Append to string
s.substr(1, 3)Substring (pos, length)
std::map<string, int> m;Sorted map (red-black tree)
std::unordered_map<string, int> m;Hash map - O(1) average lookup
m["key"] = 1; m.at("key");Insert/access - at() throws if missing
m.find("key") != m.end()Check key exists
m.count("key")1 if key exists, 0 if not (for maps)
std::set<int> s; std::unordered_set<int> us;Sorted set / hash set
std::deque<int> d;Double-ended queue
std::stack<int> st; std::queue<int> q;Stack and queue adapters
std::priority_queue<int> pq;Max-heap by default
std::pair<int, string> p = {1, "a"};Pair
std::tuple<int, string, double> t = {1, "a", 3.14};Tuple
std::get<0>(t)Access tuple element

STL Algorithms

#include <algorithm>Required header for STL algorithms
std::sort(v.begin(), v.end());Sort in ascending order
std::sort(v.begin(), v.end(), std::greater<int>());Sort descending
std::sort(v.begin(), v.end(), [](a, b){ return a < b; });Sort with custom comparator
std::find(v.begin(), v.end(), val)Find first occurrence - returns iterator
std::find_if(v.begin(), v.end(), pred)Find first matching predicate
std::count(v.begin(), v.end(), val)Count occurrences of value
std::count_if(v.begin(), v.end(), pred)Count matching predicate
std::for_each(v.begin(), v.end(), fn)Apply function to each element
std::transform(v.begin(), v.end(), out.begin(), fn)Map elements into output
std::accumulate(v.begin(), v.end(), 0)Sum (include )
std::min_element / std::max_elementIterator to min/max element
std::reverse(v.begin(), v.end())Reverse in place
std::unique(v.begin(), v.end())Remove consecutive duplicates
std::binary_search(v.begin(), v.end(), val)Binary search on sorted range
std::lower_bound / std::upper_boundFirst element >= / > value in sorted range
std::copy(src.begin(), src.end(), dst.begin())Copy range to destination
std::remove_if(v.begin(), v.end(), pred)Move non-matching to front - follow with erase

Error Handling

throw std::runtime_error("msg");Throw an exception
try { } catch (const std::exception& e) { }Catch by const reference - preferred
catch (...) { }Catch any exception type
e.what()Get exception message string
noexceptDeclare function will not throw
noexcept(expr)noexcept if expr is noexcept
std::optional<int> parse(std::string s)optional - return value or nothing
opt.has_value() / opt.value() / opt.value_or(0)Check, get, or default optional
std::expected<T, E>Expected value or error (C++23)