C++ Cheat Sheet
Syntax, STL and essential patterns — from your first program to expert C++.
30 stages · Reference fragments · By Muzammil Ayaz
STAGE 01
Absolute Beginner
#include <iostream>
int main() {
const int count = 3;
std::cout << count << "\n";
}- Initialize variables before reading them; statements end with a semicolon.
- int: integers · double: floating point · bool: true/false · char: a character.
STAGE 02
Conditions and Loops
if (n > 0) { /* positive */ }
else { /* zero or negative */ }
for (int i = 0; i < n; ++i) { /* repeat */ }
while (ready) { /* update ready */ }- Use == for comparison, = for assignment; &&, || and ! combine conditions.
- break exits a loop; continue skips to the next iteration.
STAGE 03
Functions and Modular Programming
int square(int x) { return x * x; }
void increment(int& x) { ++x; }
void inspect(const std::string& text);- Pass by value copies; a reference aliases the original.
- Recursion needs a reachable base case; declarations belong in headers.
STAGE 04
Arrays, Strings, and Data Handling
#include <vector>
#include <string>
std::vector<int> values{1, 2, 3};
values.push_back(4);
for (int x : values) { /* use x */ }- Indices run from 0 to size() - 1; at() checks bounds.
- std::getline(std::cin, text) reads spaces; vector manages dynamic storage.
STAGE 05
Pointers and Memory
#include <memory>
int x = 7;
int* p = &x;
*p = 8;
auto owner = std::make_unique<int>(9);- A pointer can be nullptr; never dereference an invalid pointer.
- Prefer RAII and unique_ptr; shared_ptr shares ownership, weak_ptr observes it.
STAGE 06
User-Defined Types and OOP
struct Point { int x{}, y{}; };
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};- struct defaults to public access; class defaults to private.
- Use virtual functions for runtime polymorphism and virtual destructors for polymorphic deletion.
STAGE 07
Files, Errors, and Debugging
#include <fstream>
#include <stdexcept>
std::ifstream file("data.txt");
if (!file) throw std::runtime_error("Open failed");
// catch (const std::exception& e) { ... }- File streams close through RAII; check stream state after I/O.
- Compile with warnings; use assertions for developer invariants, not external input validation.
STAGE 08
Standard Template Library
#include <algorithm>
std::sort(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), key);
if (it != v.end()) { /* found */ }
std::sort(v.begin(), v.end(),
[](int a, int b) { return a > b; });- vector: contiguous sequence · map/set: ordered · unordered_map/set: hash-based.
- stack: LIFO · queue: FIFO · priority_queue: largest first by default. Iterator ranges are [first, last).
STAGE 09
Modern C++
// C++17
auto [key, value] = std::pair{1, 2};
constexpr int limit = 10;
template<class T>
T twice(T x) { return x + x; }- auto deduces a type; nullptr is the typed null pointer literal.
- Move transfers resources when supported; std::move itself is a cast, not a transfer.
STAGE 10
Data Structures and Algorithms
std::sort(v.begin(), v.end());
bool found = std::binary_search(v.begin(), v.end(), key);
// BFS: queue + visited
// DFS: recursion or explicit stack
// DP: state + transition + base cases- Binary search requires sorted data: O(log n). Sorting is typically O(n log n).
- Compare time and space complexity; two pointers and sliding windows need appropriate invariants.
STAGE 11
Advanced C++ and Software Engineering
#include <mutex>
std::mutex mutex;
{
std::lock_guard<std::mutex> lock(mutex);
// shared state access
}- A data race is undefined behavior; synchronize shared mutable state.
- Use warnings, sanitizers, tests and profiling before optimizing.
STAGE 12
Practical C++ Projects
struct Task {
std::string title;
bool done = false;
};
std::vector<Task> tasks;
// parse -> validate -> update -> persist- Separate input, business rules and persistence.
- Test invalid input, empty files and edge cases for each project milestone.
STAGE 13
Beyond the Course: Contests, Algorithms, Games and Interviews
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
// prefix[i + 1] = prefix[i] + a[i]
// sum [l, r) = prefix[r] - prefix[l]- Dijkstra requires nonnegative edge weights; union-find tracks connected components.
- Use unsigned types for bit operations and verify shift counts are valid.
STAGE 14
Stacks, Queues and Deques in Depth
#include <stack>
#include <queue>
#include <deque>
std::stack<int> s; s.push(3); s.pop();
std::queue<int> q; q.push(3); q.pop();
std::deque<int> d; d.push_front(3);- Check empty() before top(), front(), back() or pop(). pop() does not return a value.
- A monotonic stack/deque discards dominated values; each element enters and leaves at most once.
STAGE 15
Linked Structures Mastery
#include <list>
std::list<int> items{1, 2};
items.push_front(0);
auto it = items.begin();
items.erase(it);- Linked lists allow O(1) insertion/erasure at a known iterator, not O(1) search.
- LRU caches combine a list with a hash map; fast/slow pointers detect cycles.
STAGE 16
Trees in Depth
// BST: left < node < right (unique keys)
// Fenwick tree, one-based indices:
for (int i = pos; i <= n; i += i & -i)
bit[i] += delta;
// pos must be >= 1- Balanced BST operations are O(log n); a skewed BST can be O(n).
- Segment/Fenwick trees support logarithmic updates and range queries; define bounds consistently.
STAGE 17
Heaps and Priority Queues
#include <queue>
#include <functional>
std::priority_queue<int> maxHeap;
std::priority_queue<int, std::vector<int>,
std::greater<int>> minHeap;
maxHeap.push(4);- top() is O(1); push()/pop() are O(log n). Check empty() before top().
- make_heap builds a heap in O(n); two heaps can maintain a running median.
STAGE 18
Hashing
#include <unordered_map>
std::unordered_map<std::string, int> counts;
++counts["cpp"];
auto it = counts.find("cpp");
if (it != counts.end()) { /* use it->second */ }- Average lookup is O(1), worst case O(n); hash collisions must be handled.
- operator[] inserts a missing key; find() checks without insertion.
STAGE 19
Graph Algorithms
using Edge = std::pair<int, int>; // to, weight
std::vector<std::vector<Edge>> graph(n);
graph[u].push_back({v, weight});
// Kahn: indegrees + queue
// MST: Kruskal + union-find- Topological order exists only for directed acyclic graphs.
- Bellman–Ford handles negative weights; Floyd–Warshall computes all-pairs shortest paths in O(n³).
STAGE 20
Dynamic Programming
// 0/1 knapsack: iterate capacity downward
for (int c = capacity; c >= weight; --c)
dp[c] = std::max(dp[c], dp[c - weight] + value);
// LCS: match -> diagonal + 1
// otherwise -> max(top, left)- Specify state meaning, base cases, transitions and evaluation order.
- Descending capacity prevents reusing one item; bitmask DP fits small state sets.
STAGE 21
String Algorithms
// KMP prefix function
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) j = pi[j - 1];
if (s[i] == s[j]) ++j;
pi[i] = j;- KMP and Z preprocess strings in O(n); define the prefix-function invariant.
- Hash equality may collide; tries store prefixes and Aho–Corasick matches multiple patterns.
STAGE 22
Advanced C++ Deep Dive
// C++20
#include <ranges>
auto even = values | std::views::filter(
[](int x) { return x % 2 == 0; });
// forwarding: std::forward<T>(value)- Views are lazy and often non-owning; keep their underlying data alive.
- Concepts constrain templates; join threads or use jthread for scoped lifetime.
STAGE 23
System Design in C++
struct Request { std::string key; };
struct Response { int status; std::string body; };
// validate -> authorize -> process -> respond
// cache: key + value + expiry
// limiter: tokens + refill time- Define ownership, errors and thread safety at API boundaries.
- Bound queues and caches; specify expiry, eviction and rate-limit behavior.
STAGE 24
Capstone Projects
#include <condition_variable>
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&] { return stop || !jobs.empty(); });
// dequeue under lock, execute outside lock- Wait with a predicate because wakeups can be spurious.
- Capstones need clear invariants: parser bounds, allocator alignment and thread-pool shutdown.
STAGE 25
Mastery Review and Final Assessment
// Complexity checklist
// sort: O(n log n)
// balanced map: O(log n) lookup
// unordered_map: average O(1) lookup
// vector index: O(1)- Recheck iterator invalidation, ownership and virtual destruction.
- Practice explaining trade-offs and testing edge cases, not only memorizing syntax.
STAGE 26
Expert Modern C++
// C++17 fold expression
template<class... Ts>
auto sum(Ts... xs) { return (xs + ... + 0); }
// C++20
consteval int square(int x) { return x * x; }- constexpr can run at compile time; consteval requires compile-time evaluation.
- variant uses visit; coroutines need a promise/lifetime design; atomics do not protect unrelated state automatically.
STAGE 27
Practical C++ Toolkit
// C++17
#include <optional>
#include <filesystem>
std::optional<int> result = 42;
if (result) { /* use *result */ }
auto exists = std::filesystem::exists("data.txt");- string_view (C++17) and span (C++20) are non-owning; avoid dangling views.
- steady_clock measures elapsed time; regex needs escaping; filesystem operations can throw or take error_code.
STAGE 28
Game Development in C++
struct Vec2 { double x, y; };
// game loop: input -> update(dt) -> render
pos = pos + vel * dt;
// AABB: a.x < b.x + b.w && b.x < a.x + a.w
// && a.y < b.y + b.h && b.y < a.y + a.h- Use a fixed time step so movement is per second, not per frame.
- Keep render read-only; ECS stores plain-data components and puts logic in systems.
STAGE 29
Performance Engineering
#include <chrono>
auto start = std::chrono::steady_clock::now();
// measured work; consume its result afterward
auto elapsed = std::chrono::steady_clock::now() - start;
values.reserve(expectedCount);
// range sum [l,r): prefix[r] - prefix[l]- Measure representative optimized workloads repeatedly; report noise and correctness evidence.
- reserve changes capacity, not size; layout and algorithm choice follow actual access patterns.
STAGE 30
Build Your Own Interpreter
// source -> tokens -> syntax -> evaluation
// expression = term ((+ | -) term)*
// term = atom ((* | /) atom)*
// atom = integer | name | (expression) | -atom
std::map<std::string, double> environment;
// read via find; assign only after a valid statement- Keep line and column locations; reject unknown symbols and trailing tokens.
- Use owned AST nodes, explicit environments and controlled errors; a tiny interpreter is not a full C++ compiler.