C++

Basics

#include <iostream>I/O library
#include <string>String library
#include <vector>Dynamic array
using namespace std;Standard namespace
int main() { return 0; }Entry point
std::cout << "text"Print to console
std::cin >> varRead from console
std::endlNewline + flush

Data Types

int32-bit integer
long long64-bit integer
double64-bit float
float32-bit float
charSingle character
booltrue/false
std::stringString type
autoType inference
constConstant value
unsignedNon-negative only
size_tUnsigned size type
nullptrNull pointer

STL Containers

vector<T> vDynamic array
v.push_back(x)Add to end
v.size()Number of elements
v[i] / v.at(i)Access element
v.begin() / v.end()Iterators
map<K,V> mOrdered key-value map
unordered_map<K,V>Hash map (faster)
set<T> / unordered_set<T>Unique elements
stack<T> / queue<T>LIFO / FIFO
deque<T>Double-ended queue
pair<A,B> pTwo-value tuple
array<T, N>Fixed-size array

Strings

s.length() / s.size()String length
s.substr(pos, len)Substring
s.find("sub")Find substring position
s.append(str)Concatenate
s + " text"String concatenation
s.compare(other)Compare strings
std::to_string(n)Number to string
std::stoi(s)String to int
s.c_str()C-style string pointer

Control Flow

if (cond) { } else { }If-else statement
switch (val) { case: }Switch statement
for (int i=0; i<n; i++)For loop
for (auto& x : container)Range-based for
while (cond) { }While loop
break / continueExit / skip loop
cond ? a : bTernary operator

Functions

int fn(int a, int b)Function with return
void fn()No return value
int fn(int a = 5)Default parameter
void fn(int& ref)Pass by reference
void fn(const int& x)Const reference
auto fn() -> intTrailing return type
template<typename T>Function template
[](int x) { return x*2; }Lambda expression

Pointers & Memory

int* ptr = &varPointer to variable
*ptrDereference pointer
int& ref = varReference to variable
new int(5)Heap allocation
delete ptrFree heap memory
std::unique_ptr<T>Unique ownership
std::shared_ptr<T>Shared ownership
std::make_unique<T>()Create unique_ptr
std::make_shared<T>()Create shared_ptr

Classes

class MyClass { };Class definition
public: / private:Access specifiers
MyClass() { }Constructor
~MyClass() { }Destructor
class B : public AInheritance
virtual void fn()Virtual method
overrideExplicit override
static int countStatic member

STL Algorithms

sort(v.begin(), v.end())Sort container
reverse(v.begin(), v.end())Reverse container
find(v.begin(), v.end(), x)Find element
count(v.begin(), v.end(), x)Count occurrences
accumulate(v.begin(), v.end(), 0)Sum elements
min_element / max_elementMin/max iterator
binary_search(b, e, val)Binary search
transform(b, e, out, fn)Apply function
allprintabledoc.com