Basics
#include <iostream>Include standard I/O headerusing namespace std;Use standard namespace (avoid in headers)int main() { return 0; }Entry point - return 0 means successstd::cout << "Hello" << std::endl;Print to stdoutstd::cin >> x;Read from stdin// single line commentSingle-line comment/* multi line */Multi-line commentint x = 5; double d = 3.14; bool b = true; char c = 'A';Common typesauto x = 42;auto - infer type from initializerconst int MAX = 100;Compile-time constantconstexpr int SQ = 10 * 10;constexpr - evaluated at compile timeint x {5};Brace initialization - prevents narrowingnullptrNull pointer constant (use instead of NULL)sizeof(int)Size in bytes of type or variablestatic_cast<double>(x)Safe explicit castPointers & References
int* p = &x;Pointer to int, initialized to address of x*pDereference pointer - access valuep->memberAccess member via pointer (same as (*p).member)int& ref = x;Reference - alias for x, cannot be reboundvoid swap(int& a, int& b)Pass by reference - modifies caller variableconst int& r = x;Const reference - read-only aliasint arr[5] = {1, 2, 3, 4, 5};Stack-allocated arrayint* p = new int(42);Heap allocationdelete p; p = nullptr;Free heap memory - set to nullptr afterint* arr = new int[10];Heap arraydelete[] arr;Free heap arrayint** pp = &p;Pointer to pointerint& arr[5](invalid) - prefer std::array or spanSmart Pointers
#include <memory>Required header for smart pointersauto p = std::make_unique<int>(42);unique_ptr - sole owner, auto-deletedauto p = std::make_shared<User>("Alice");shared_ptr - reference-counted shared ownershipstd::weak_ptr<User> wp = sp;weak_ptr - non-owning reference to shared_ptrif (auto locked = wp.lock()) { }Lock weak_ptr to get shared_ptr (check for null)p.get()Get raw pointer (do not delete it)p.reset()Release ownership - destroys managed objectstd::move(p)Transfer unique_ptr ownershipControl Flow
if (x > 0) { } else if (x < 0) { } else { }if / else if / elseswitch (x) { case 1: break; default: break; }switch - fallthrough unless breakfor (int i = 0; i < n; i++) { }C-style for loopfor (auto& item : vec) { }Range-based for - iterate over containerfor (const auto& [key, val] : map) { }Structured bindings in range-for (C++17)while (x > 0) { }while loopdo { } while (x > 0);do-while loopbreak / continueExit loop / skip to next iteration[[likely]] / [[unlikely]]Branch prediction hints (C++20)Functions
int add(int a, int b) { return a + b; }Function definitionint add(int a, int b = 0)Default argument (rightmost only)void swap(int& a, int& b)Pass by referenceint process(const std::string& s)Pass by const reference - efficient, read-onlyauto add(int a, int b) -> intTrailing return typeinline int sq(int x) { return x * x; }Inline - suggest inlining at call sitestemplate<typename T> T max(T a, T b)Function templatetemplate<typename T, typename U>Multiple template parametersauto fn = [](int x) { return x * 2; };Lambda expression[&](int x) { return x + y; }Lambda capturing by reference[=](int x) { return x + y; }Lambda capturing by value[x, &y](int z) { }Lambda capturing specific variablesstd::function<int(int)> fnStore any callable with signature int(int)[[nodiscard]] int parse()Warn if return value is discardedClasses & OOP
class User { public: std::string name; };Class - members private by defaultstruct Point { int x; int y; };Struct - members public by defaultUser(std::string n) : name(std::move(n)) {}Constructor with member initializer list~User() { }Destructor - called on object destructionUser(const User& other)Copy constructorUser(User&& other) noexceptMove constructorUser& operator=(const User& other)Copy assignment operatorUser& operator=(User&& other) noexceptMove assignment operator= default; / = delete;Use compiler-generated / disable special memberclass Admin : public User { };Public inheritancevirtual void speak() { }Virtual method - overridable in derived classvirtual void speak() = 0;Pure virtual - abstract classvoid speak() override { }Override virtual method - override keyword prevents mistakesvoid speak() final { }final - cannot be further overriddentemplate<typename T> class Box { T value; };Class templatefriend class Admin;Grant another class access to private membersSTL Containers
std::vector<int> v = {1, 2, 3};Dynamic arrayv.push_back(4); v.emplace_back(5);Append elementv.pop_back();Remove last elementv[i] / v.at(i)Access element - at() bounds-checksv.size() / v.empty()Size and empty checkv.reserve(100);Pre-allocate capacitystd::array<int, 5> arr = {1,2,3,4,5};Fixed-size array with STL interfacestd::string s = "hello";Dynamic strings += " world"; s.append("!");Append to strings.substr(1, 3)Substring (pos, length)std::map<string, int> m;Sorted map (red-black tree)std::unordered_map<string, int> m;Hash map - O(1) average lookupm["key"] = 1; m.at("key");Insert/access - at() throws if missingm.find("key") != m.end()Check key existsm.count("key")1 if key exists, 0 if not (for maps)std::set<int> s; std::unordered_set<int> us;Sorted set / hash setstd::deque<int> d;Double-ended queuestd::stack<int> st; std::queue<int> q;Stack and queue adaptersstd::priority_queue<int> pq;Max-heap by defaultstd::pair<int, string> p = {1, "a"};Pairstd::tuple<int, string, double> t = {1, "a", 3.14};Tuplestd::get<0>(t)Access tuple elementSTL Algorithms
#include <algorithm>Required header for STL algorithmsstd::sort(v.begin(), v.end());Sort in ascending orderstd::sort(v.begin(), v.end(), std::greater<int>());Sort descendingstd::sort(v.begin(), v.end(), [](a, b){ return a < b; });Sort with custom comparatorstd::find(v.begin(), v.end(), val)Find first occurrence - returns iteratorstd::find_if(v.begin(), v.end(), pred)Find first matching predicatestd::count(v.begin(), v.end(), val)Count occurrences of valuestd::count_if(v.begin(), v.end(), pred)Count matching predicatestd::for_each(v.begin(), v.end(), fn)Apply function to each elementstd::transform(v.begin(), v.end(), out.begin(), fn)Map elements into outputstd::accumulate(v.begin(), v.end(), 0)Sum (include std::min_element / std::max_elementIterator to min/max elementstd::reverse(v.begin(), v.end())Reverse in placestd::unique(v.begin(), v.end())Remove consecutive duplicatesstd::binary_search(v.begin(), v.end(), val)Binary search on sorted rangestd::lower_bound / std::upper_boundFirst element >= / > value in sorted rangestd::copy(src.begin(), src.end(), dst.begin())Copy range to destinationstd::remove_if(v.begin(), v.end(), pred)Move non-matching to front - follow with eraseError Handling
throw std::runtime_error("msg");Throw an exceptiontry { } catch (const std::exception& e) { }Catch by const reference - preferredcatch (...) { }Catch any exception typee.what()Get exception message stringnoexceptDeclare function will not thrownoexcept(expr)noexcept if expr is noexceptstd::optional<int> parse(std::string s)optional - return value or nothingopt.has_value() / opt.value() / opt.value_or(0)Check, get, or default optionalstd::expected<T, E>Expected value or error (C++23)