Skip to main content

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.

Quick Reference

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)

TypeBytesNotes
bool1true / false
char1Character / small integer
int4Default integer
long long8Wide integer
float / double4 / 8Prefer double
size_t8*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

KindExamples
Arithmetic+ - * / %
Relational== != < > <= >=
Logical&& || ! (short-circuit)
Bitwise& | ^ ~ << >>
Assignment= += -= *= /=
Inc / Dec++i / i++
Ternarycond ? a : b
Othersizeof, ::, .*

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

FeaturePointerReference
Null?Yes (nullptr)No (must bind)
Reseat?YesNo
Syntax*p / &xT& r = x
ArithmeticYesNo

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&);
};
IdeaCheat note
struct vs classDefault access public vs private
Encapsulationprivate data + public API
thisPointer to current object
Static membersShared by all instances
FriendAccess private; use sparingly
Constructors / DestructorsInit and RAII cleanup
Rule of Zero/FiveRAII types or define/delete specials
= default / = deleteGenerate 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++; };
CastUse
static_castRelated conversions
dynamic_castSafe polymorphic downcast
const_castAdd/remove const
reinterpret_castLow-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

ContainerHeaderNotes
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
AdapterOrderHeader
stackLIFO<stack>
queueFIFO<queue>
priority_queueMax-heap (default)<queue>

stack<int> st; st.push(1); st.top(); st.pop();
priority_queue<int, vector<int>, greater<int>> minh;

Gotchas & Interview Traps

TrapRemember
map[k] missing keyInserts default — use find/at
Non-virtual base destructorDeleting via base* is UB
Object slicingPass polymorphic types by pointer/ref
delete vs delete[]Must match new / new[]
Moved-from objectValid but unspecified
string_view lifetimeMust not outlive source
STL heap ≠ heap memoryDifferent meanings
multiset.erase(key)Removes all equals
Lambda [&]Watch dangling references
Integer division5/2 == 2

How to use: skim jump chips → drill tables → type every snippet once. Pair with Interview Q&A for spoken answers.