C++C++ · Lesson 9 of 9

C++ Cheatsheet

Modern C++ (17/20) on one page — RAII, STL, smart pointers.

C++
// ── Basics ──────────────────────────────
#include <iostream>
#include <string>
#include <vector>

int main() {
    int x = 42;
    double pi = 3.14;
    std::string name = "Ada";
    auto y = 3.14f;              // type inference
    const int LIMIT = 100;
    std::cout << name << " is " << x << "\n";
}

// ── Control flow ────────────────────────
if (x > 10) { } else if (x > 5) { } else { }
for (int i = 0; i < 5; i++) { }
for (const auto& item : items) { }    // range-for
while (cond) { }
auto label = x > 10 ? "big" : "small";

// ── Functions ───────────────────────────
int add(int a, int b = 0) { return a + b; }
void grow(std::vector<int>& v);       // reference: no copy
int sum(const std::vector<int>& v);   // const ref: read-only
auto square = [](int n) { return n * n; };   // lambda
auto addN = [n](int x) { return x + n; };    // capture
C++
// ── STL containers ──────────────────────
std::vector<int> v = {3, 1, 4};
v.push_back(1); v[0]; v.size(); v.empty();
std::map<std::string, int> ages{{"Ada", 17}};
ages["Bob"] = 15; ages.count("Eve");
std::unordered_map<std::string, int> fast;  // hash map
std::set<int> seen;

// ── Algorithms ──────────────────────────
#include <algorithm>
std::sort(v.begin(), v.end());
std::find(v.begin(), v.end(), 4);
std::count_if(v.begin(), v.end(), [](int n){ return n > 2; });
auto it = std::max_element(v.begin(), v.end());

// ── Classes & RAII ──────────────────────
class Dog {
    std::string name_;
public:
    explicit Dog(std::string name) : name_(std::move(name)) {}
    std::string bark() const { return name_ + " woofs"; }
    ~Dog() { /* cleanup runs automatically */ }
};

// ── Smart pointers (never raw new/delete) ──
#include <memory>
auto dog = std::make_unique<Dog>("Rex");   // sole owner
auto shared = std::make_shared<Dog>("Fido"); // ref-counted
// std::move transfers ownership of a unique_ptr

// ── Modern extras ───────────────────────
std::optional<int> maybe;        // value-or-nothing
if (maybe) use(*maybe);
std::string_view sv = name;      // non-owning string ref
struct Point { int x, y; };
auto [px, py] = Point{1, 2};     // structured bindings

// g++ -std=c++20 -Wall -O2 main.cpp -o app