Learning Resources
Cheatsheet
A complete C++ cheatsheet — every major concept in one page: basics, control flow, OOP, modern features, and the STL. Ideal for last-minute revision and day-to-day lookup.
C++ Programming Cheatsheet
Every major C++ concept on one page — basics, OOP, modern features, and the STL — with tables and the smallest working snippets. Built for revision before interviews and for looking things up while you code.
Program Structure & I/O
Minimal program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!\n";
return 0;
}
Compile and run
g++ -std=c++17 -Wall -Wextra main.cpp -o app
g++ -std=c++20 -O2 main.cpp -o app
./app
cin / cout essentials
int n; double x; string s;
cin >> n >> x;
getline(cin, s);
cout << n << ' ' << x << '\n';
cout << fixed << setprecision(2) << x; // <iomanip>
Tip: Prefer std:: in libraries; using namespace std; is fine for small demos.
Data Types, Variables & Constants
Common types (typical 64-bit)
| Type | Bytes | Notes |
|---|---|---|
bool | 1 | true / false |
char | 1 | Character / small integer |
int | 4 | Default integer |
long long | 8 | Wide integer |
float / double | 4 / 8 | Prefer double |
size_t | 8* | Sizes / indexes |
nullptr | — | Typed null pointer (C++11) |
const / constexpr / auto / enum class
const int MAX = 100;
constexpr int SQ = 25;
auto x = 3.14;
enum class Color { Red, Green, Blue };
Color c = Color::Red;
Operators
| Kind | Examples |
|---|---|
| Arithmetic | + - * / % |
| Relational | == != < > <= >= |
| Logical | && || ! (short-circuit) |
| Bitwise | & | ^ ~ << >> |
| Assignment | = += -= *= /= |
| Inc / Dec | ++i / i++ |
| Ternary | cond ? a : b |
| Other | sizeof, ::, .* |
Cannot overload: :: . .* ?:. Avoid overloading && / ||.
Control Flow
if (x > 0) { ... }
else if (x == 0) { ... }
else { ... }
switch (k) {
case 1: ...; break;
default: ...;
}
for (int i = 0; i < n; ++i) { ... }
while (cond) { ... }
do { ... } while (cond);
for (auto& x : container) { ... }
break; continue;
Arrays
int a[5] = {1, 2, 3};
int m[2][3];
#include <array>
array<int, 4> arr = {1, 2, 3, 4};
C-arrays decay to pointers and have no bounds checks. Prefer vector / array.
Strings (std::string)
#include <string>
string s = "hi";
s += " there";
s.size(); s.empty(); s.substr(0, 2);
s.find("th"); // npos if missing
stoi("42"); to_string(42);
string_view sv = s; // non-owning — do not outlive s
Functions & Recursion
int add(int a, int b = 0);
void f(const string& s); // const ref
void g(int& x); // modify caller
int abs(int); double abs(double); // overload
int fact(int n) {
return n <= 1 ? 1 : n * fact(n - 1);
}
Pointers & References
| Feature | Pointer | Reference |
|---|---|---|
| Null? | Yes (nullptr) | No (must bind) |
| Reseat? | Yes | No |
| Syntax | *p / &x | T& r = x |
| Arithmetic | Yes | No |
int x = 10;
int* p = &x; *p = 20;
int& r = x; r = 30;
int* q = nullptr;
Namespaces, Structures & Unions
namespace util { int clamp(int x); }
util::clamp(5);
namespace u = util;
struct Point { int x, y; }; // public by default
union U { int i; float f; };
File Handling & Command Line
#include <fstream>
ofstream out("out.txt");
out << "line\n";
ifstream in("out.txt");
string line;
while (getline(in, line)) cout << line << '\n';
int main(int argc, char* argv[]) { ... }
OOP — Classes & Objects
class Account {
public:
explicit Account(int bal) : balance(bal) {}
~Account() = default;
int get() const { return balance; }
static int count;
private:
int balance;
friend void audit(Account&);
};
| Idea | Cheat note |
|---|---|
| struct vs class | Default access public vs private |
| Encapsulation | private data + public API |
this | Pointer to current object |
| Static members | Shared by all instances |
| Friend | Access private; use sparingly |
| Constructors / Destructors | Init and RAII cleanup |
| Rule of Zero/Five | RAII types or define/delete specials |
= default / = delete | Generate or forbid specials |
Inheritance, Abstraction & Polymorphism
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};
class Circle : public Shape {
public:
double area() const override;
};
Shape* p = new Circle(...);
p->area();
delete p; // needs virtual ~Shape
Keywords: virtual, override, final, access levels. Diamond problem → virtual inheritance. Overload = compile-time; override = runtime.
Modern C++ — RAII, Smart Ptrs, Move, Lambda
Smart pointers & RAII
#include <memory>
auto u = make_unique<T>(...); // exclusive
auto s = make_shared<T>(...); // shared
weak_ptr<T> w = s; // non-owning / break cycles
Move & lambda
T b = std::move(a);
auto f = [=](int x) { return x + 1; };
auto g = [&out]() { out++; };
| Cast | Use |
|---|---|
static_cast | Related conversions |
dynamic_cast | Safe polymorphic downcast |
const_cast | Add/remove const |
reinterpret_cast | Low-level (rare) |
Templates & Exceptions
template<typename T>
T maxv(T a, T b) { return a > b ? a : b; }
try {
throw runtime_error("fail");
} catch (const exception& e) {
cerr << e.what();
}
Catch by const&. Member function templates cannot be virtual.
STL Containers
| Container | Header | Notes |
|---|---|---|
vector | <vector> | Dynamic array — default choice |
deque | <deque> | Fast insert/erase at both ends |
list / forward_list | <list> | Doubly / singly linked |
set / multiset | <set> | Sorted unique / duplicates |
unordered_set | <unordered_set> | Hash unique membership |
map / multimap | <map> | Sorted key→value |
unordered_map | <unordered_map> | Hash map / counters |
pair / tuple | <utility> / <tuple> | Fixed-size groups |
vector<int> v = {1, 2, 3};
v.push_back(4);
map<string, int> ages;
ages["Ann"] = 20; // may insert
unordered_map<string, int> freq;
freq["hi"]++;
Algorithms, Iterators, Heaps & Adapters
#include <algorithm>
sort(v.begin(), v.end());
stable_sort(v.begin(), v.end());
find(v.begin(), v.end(), x);
lower_bound(v.begin(), v.end(), x); // needs sorted
min(a, b); max_element(v.begin(), v.end());
make_heap(v.begin(), v.end());
push_heap / pop_heap / sort_heap / is_heap
| Adapter | Order | Header |
|---|---|---|
stack | LIFO | <stack> |
queue | FIFO | <queue> |
priority_queue | Max-heap (default) | <queue> |
stack<int> st; st.push(1); st.top(); st.pop();
priority_queue<int, vector<int>, greater<int>> minh;
Gotchas & Interview Traps
| Trap | Remember |
|---|---|
map[k] missing key | Inserts default — use find/at |
| Non-virtual base destructor | Deleting via base* is UB |
| Object slicing | Pass polymorphic types by pointer/ref |
delete vs delete[] | Must match new / new[] |
| Moved-from object | Valid but unspecified |
string_view lifetime | Must not outlive source |
| STL heap ≠ heap memory | Different meanings |
multiset.erase(key) | Removes all equals |
Lambda [&] | Watch dangling references |
| Integer division | 5/2 == 2 |
How to use: skim jump chips → drill tables → type every snippet once. Pair with Interview Q&A for spoken answers.