C++ Cheat Sheet
C++ reference with STL containers, smart pointers, templates, lambdas, and modern C++17/20 features. Copy-ready code examples.
Variables
| Syntax | Description | Example |
|---|---|---|
| Integer variable | int count = 0; | |
| Floating-point variable | double pi = 3.14159; | |
| Character variable | char grade = 'A'; | |
| Boolean variable | bool isValid = true; | |
| Type inference (C++11) | auto name = std::string("Alice"); | |
| Compile-time constant | const int MAX = 100; | |
| Compile-time expression (C++11) | constexpr double pi = 3.14159; | |
| Print to console | std::cout << "Hello " << name << std::endl; | |
| Read from console | std::cin >> age; | |
| Type alias | using StringVec = std::vector<std::string>; | |
| Safe type casting | int x = static_cast<int>(3.14); | |
| Size in bytes | sizeof(int) // usually 4 |
Strings
| Syntax | Description | Example |
|---|---|---|
| String object | std::string name = "Alice"; | |
| String length | name.length() // 5 | |
| Extract substring | "hello".substr(1, 3) // "ell" | |
| Find substring position | s.find("ll") // 2, npos if not found | |
| Replace portion of string | s.replace(0, 5, "Hi") | |
| Concatenate strings | s += " World"; | |
| Get C-style string | const char* cs = s.c_str(); | |
| Check if empty | if (s.empty()) { ... } | |
| Number to string | std::to_string(42) // "42" | |
| String to number | int n = std::stoi("42"); | |
| Non-owning string reference (C++17) | void print(std::string_view sv) { ... } |
Containers
| Syntax | Description | Example |
|---|---|---|
| Dynamic array | std::vector<int> nums = {1, 2, 3}; | |
| Add element to end | nums.push_back(4); | |
| Remove last element | nums.pop_back(); | |
| Size / check empty | if (nums.empty()) { ... } | |
| Access element (at() throws on OOB) | int x = nums.at(0); | |
| Iterator begin/end | for (auto it = v.begin(); it != v.end(); ++it) | |
| Fixed-size array (C++11) | std::array<int, 3> arr = {1, 2, 3}; | |
| Ordered key-value map | std::map<std::string, int> ages; | |
| Hash map (O(1) lookup) | std::unordered_map<std::string, int> cache; | |
| Ordered set (unique values) | std::set<int> unique_nums; | |
| Hash set | std::unordered_set<std::string> seen; | |
| Pair of values | auto p = std::make_pair(1, "hello"); | |
| Tuple (multiple values) | auto t = std::make_tuple(1, 3.14, "hi"); | |
| Optional value (C++17) | std::optional<int> find(int id) { ... } | |
| Stack / Queue adapters | std::stack<int> s; s.push(1); s.top(); |
Control Flow
| Syntax | Description | Example |
|---|---|---|
| Conditional branching | if (x > 0) { ... } else { ... } | |
| If with initializer (C++17) | if (auto it = m.find(k); it != m.end()) { ... } | |
| Switch statement | switch (day) { case 1: ... break; default: ... } | |
| For loop | for (int i = 0; i < 10; i++) { ... } | |
| Range-based for (C++11) | for (const auto& item : vec) { ... } | |
| While loop | while (count < 10) { count++; } | |
| Exception handling | try { ... } catch (const std::exception& e) { ... } | |
| Throw exception | throw std::runtime_error("error"); |
Functions
| Syntax | Description | Example |
|---|---|---|
| Function definition | int add(int a, int b) { return a + b; } | |
| Inline hint for compiler | inline int square(int x) { return x*x; } | |
| Lambda expression (C++11) | auto double_it = [](int x) { return x * 2; }; | |
| Lambda capture modes | [&sum](int x) { sum += x; } | |
| Function/class template | template<typename T> T max(T a, T b) { return a>b ? a : b; } | |
| Compile-time evaluation | constexpr int factorial(int n) { return n<=1 ? 1 : n*factorial(n-1); } | |
| Type-erased callable | std::function<int(int)> fn = [](int x) { return x*2; }; |
OOP
| Syntax | Description | Example |
|---|---|---|
| Define a class | class User { public: std::string name; }; | |
| Access specifiers | class Foo { private: int x; public: int getX(); }; | |
| Constructor | User(std::string n) : name(std::move(n)) {} | |
| Destructor | ~FileHandler() { close(); } | |
| Inheritance | class Admin : public User { int level; }; | |
| Virtual method (polymorphism) | virtual void draw() = 0; // pure virtual | |
| Mark overriding method (C++11) | void draw() override { ... } | |
| Class-level member | static int count; |
Memory
| Syntax | Description | Example |
|---|---|---|
| Exclusive ownership pointer | auto p = std::make_unique<User>("Alice"); | |
| Shared ownership pointer | auto p = std::make_shared<User>("Alice"); | |
| Non-owning reference to shared | std::weak_ptr<User> wp = sp; | |
| Transfer ownership | auto p2 = std::move(p1); // p1 is now null |
Modern C++
| Syntax | Description | Example |
|---|---|---|
| Type deduction | auto x = 42; auto it = map.begin(); | |
| Null pointer literal (C++11) | int* p = nullptr; | |
| Scoped enumeration (C++11) | enum class Color { Red, Green, Blue }; | |
| Destructure (C++17) | auto [key, value] = *map.begin(); | |
| Type-safe union (C++17) | std::variant<int, std::string> val = 42; | |
| Constrain templates | template<std::integral T> T add(T a, T b); | |
| Composable range operations | auto evens = nums | std::views::filter([](int x){ return x%2==0; }); |
Frequently asked questions
What's the difference between C and C++?
C++ is a superset of C that adds classes, templates, RAII, smart pointers, STL containers, exceptions, and much more. C is simpler and used for systems programming, kernels, and embedded. C++ is used for games, desktop apps, and performance-critical software.
When should I use unique_ptr vs shared_ptr?
unique_ptr for sole ownership (default choice, zero overhead). shared_ptr when multiple owners need to share the same resource (adds reference counting overhead). Use weak_ptr to break circular references with shared_ptr.
What is RAII?
Resource Acquisition Is Initialization - a pattern where resources (memory, files, locks) are acquired in constructors and released in destructors. This guarantees cleanup even when exceptions occur. Smart pointers, lock_guard, and fstream all use RAII.
What C++ standard should I target?
C++17 minimum for new projects - it adds structured bindings, std::optional, string_view, and if-init. C++20 adds concepts, ranges, coroutines, and modules. C++23 is latest. Avoid pre-C++11 patterns.
How do templates work?
Templates generate code at compile time for each type used. template<typename T> creates a generic function or class. The compiler creates specialized versions (int, string, etc.) as needed. This enables zero-cost abstractions.
What are move semantics?
Move semantics (C++11) allow transferring resources instead of copying. std::move converts an object to an rvalue reference, enabling move constructors/assignment operators. This is critical for performance with large objects like vectors and strings.
Go from reference to real skills
Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.
Browse all courses