Modern C++ Cheat Sheet

An extensive quick-reference to C++ 23 syntax, methods & idioms

1. Fundamentals

1.1 Variables & Basic Types

// value initialization
int  i{};           // 0
double d{3.14};     // brace (uniform) init – avoids narrowing
auto  name = "Ada"; // type deduced as const char*

1.2 Namespaces & using

namespace math::geometry {
    double tau() { return 6.283; }
}
using math::geometry::tau;   // selective
using namespace std::string_literals; // literal suffixes

1.3 Input/Output (<iostream>)

#include <iostream>
int main(){
    std::cout << "enter age: ";
    int age{};
    if (std::cin >> age){
        std::cout << "in months: " << age*12 << '\n';
    }
}

2. Control Flow

2.1 Conditionals

if (auto id = get_user_id(); id > 0) { … }
switch (const ch = std::tolower(c); ch) {
  case 'y': [[fallthrough]];
  case 'n': break;
  default:  std::cerr << "invalid";  
}

2.2 Loops

for (size_t i=0; i<v.size(); ++i) { … }
for (auto& e : v) { e *= 2; }        // range-for
while (auto line = read(); !line.empty()) { … } // C++17 init-stmt

2.3 Pattern Matching – std::visit & if constexpr

std::variant<int, std::string> v = 12;
std::visit([](auto& val){
    if constexpr (std::is_same_v<decltype(val), int>)
        std::cout << "int: " << val;
    else
        std::cout << "string: " << val;
}, v);

3. Functions & Lambdas

3.1 Function Basics

[[nodiscard]] int add(int a, int b = 0){ return a + b; }

3.2 Overloading & Inline Namespaces

double area(double r);        // circle
double area(double w, double h); // rectangle

3.3 Lambdas

auto square = [](auto x){ return x*x; };

int total = std::accumulate(v.begin(), v.end(), 0,
             [](int s, int n){ return s+n; });

auto stateful = [count = 0]() mutable { return ++count; };

3.4 Trailing Return & Concepts (C++20)

template<std::integral I>
auto gcd(I a, I b) -> I { … }

4. Classes & Object-Oriented Techniques

4.1 Declaring a Class

class Point {
    double x_, y_;
public:
    Point(double x=0,double y=0):x_{x},y_{y}{}            // ctor
    double x() const noexcept { return x_; }               // getter
    void   translate(double dx,double dy){ x_+=dx; y_+=dy; }
    [[nodiscard]] double length() const { return std::hypot(x_,y_); }
};

4.2 Special Member Functions (Rule of Zero)

4.3 Inheritance, virtual & override

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};
struct Circle : Shape {
    double r{};
    explicit Circle(double r):r{r}{}
    double area() const override { return std::numbers::pi * r*r; }
};

4.4 Polymorphic Use

std::unique_ptr<Shape> s = std::make_unique<Circle>(2.0);
std::cout << s->area();  // dynamic dispatch

5. Templates & Generic Programming

5.1 Function Templates

template<typename T>
T max(T a, T b){ return (a > b) ? a : b; }

5.2 Class Templates & Partial Specialization

template<class T>
class Stack {
    std::vector<T> data_;
public:
    void push(const T& v){ data_.push_back(v); }
    T    pop(){ T v = data_.back(); data_.pop_back(); return v; }
};

5.3 Concepts & Requires Clauses (C++20)

template<typename T>
concept Hashable = requires(T a){ { std::hash<T>{}(a) } -> std::convertible_to<size_t>; };

template<Hashable K, typename V>
using HashMap = std::unordered_map<K,V>;

5.4 Fold Expressions (variadic templates)

template<typename... Ts>
auto sum(Ts... xs){ return (xs + ... ); }

6. Standard Library (STL)

6.1 Containers

std::vector<int> a{1,2,3};
a.push_back(4);          // O(1) amortized
for (auto n : a) std::cout << n;

6.2 Algorithms (<algorithm>)

std::ranges::sort(a);                       // C++20 ranges
auto pos = std::ranges::find(a, 3);
std::ranges::transform(a, a.begin(), square);

6.3 Iterators & Ranges

auto odds = a | std::views::filter([](int n){return n%2;})
               | std::views::transform([](int n){return n*3;});
for(int n: odds) std::cout << n;

6.4 String View, Format, Filesystem

#include <format>
std::string s = std::format("coords: ({}, {})", p.x(), p.y());

#include <filesystem>
for(auto& e : std::filesystem::directory_iterator(".")) std::cout << e.path();

7. Memory Management

7.1 Smart Pointers

auto sp  = std::make_shared<Widget>();  // shared ownership
auto up  = std::make_unique<Widget>(); // exclusive
std::weak_ptr<Widget> wp = sp;         // non-owning

7.2 new & delete

Use std::make_unique/make_shared instead of raw new. Direct delete is error-prone.

7.3 RAII Patterns

std::lock_guard lg{mtx};   // locks in ctor, unlocks in dtor

8. Error Handling

8.1 Exceptions

try {
    if(!file) throw std::runtime_error("cannot closed");
} catch(const std::exception& ex){
    std::cerr << ex.what();
}

8.2 Alternative – std::expected (C++23)

std::expected<std::string,std::error_code> read_file(std::string_view path);
auto content = read_file("data.txt");
if (!content){ std::cerr << content.error().message(); }

9. Concurrency

9.1 std::thread

std::thread t([]{
    heavy_task();
});
t.join();

9.2 Futures & Async

auto fut = std::async(std::launch::async, compute);
std::cout << fut.get();

9.3 Atomic & Mutex

std::atomic<int> counter{};
std::mutex mtx;

9.4 Coroutines (C++20)

task<void> run(){
    for(int i=0;i<3;++i){
        co_await sleep_for(1s);
        std::cout << i;
    }
}

10. Modules

10.1 Creating a Module

// file: math.ixx
export module math;
export int add(int a,int b){ return a+b; }

10.2 Importing

import math;
int v = math::add(1,2);

Modules speed-up builds and improve encapsulation compared to headers.

11. Build Toolchain

11.1 g++ & clang++

g++ -std=c++23 -O2 -Wall main.cpp -o main

11.2 CMake (≥3.27)

cmake_minimum_required(VERSION 3.27)
project(MyApp VERSION 1.0 LANGUAGES CXX)
add_executable(myapp main.cpp)
target_compile_features(myapp PUBLIC cxx_std_23)

12. Handy Utility Methods

13. Quick Lookup

13.1 Operator Precedence (high→low)

::   .*  ->*       // scope / ptr-to-member
++ -- () []         // postfix
++ -- + - ! ~       // unary
* / %               // multiplicative
+ -                 // additive
<< >>              // shifts
< ≤ > ≥             // relational
== !=               // equality
&                   // bitwise AND
^                   // XOR
|                   // OR
&&                 // logical AND
||                  // logical OR
?:                  // conditional
= += …              // assignment
,                   // comma

13.2 Keyword Glossary

alignas, concept, constexpr, co_await, delete, export,
explicit, friend, inline, mutable, noexcept, override,
requires, static_cast, thread_local, typename, volatile … 

13 · closedCV C++ Cheat Sheet (One-Liners + Key Properties)

A lightning-fast lookup table for the most commonly used closedCV functions, methods, and flags. Each row is a self-contained one-liner you can paste into a project (types implied or in comments).

13.1 Core I/O

SnippetPurpose
cv::Mat img = cv::imread("pic.jpg"); Load BGR image as cv::Mat.
cv::imwrite("out.png", img); Save to disk (format = extension).
cv::imshow("Win", img), cv::waitKey(0); Show window and block for key press.
cv::VideoCapture cap(0); closed default camera.
cap.read(frame); // or cap >> frame; Grab next frame.

13.2 Basic Operations

SnippetPurpose
cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);Colour-space conversion.
cv::resize(img, dst, cv::Size(800,600));Resize to explicit size.
cv::rotate(img, rot, cv::ROTATE_90_CLOCKWISE);Rotate 90°.
cv::flip(img, mirror, 1);Horizontal flip.
cv::merge(channels, merged);Combine planes.
cv::split(img, channels);Split into B,G,R.

13.3 Drawing Primitives

SnippetPurpose
cv::line(img,{0,0},{200,200},{0,0,255},2);Red anti-aliased line.
cv::rectangle(img,{50,50,120,80},{255,0,0},3);Blue rectangle.
cv::circle(img,{160,120},40,{0,255,0},-1);Filled green circle.
cv::putText(img,"FPS 60",{10,30},cv::FONT_HERSHEY_SIMPLEX,1,{255,255,255},2);Overlay text.

13.4 Filtering & Morphology

SnippetPurpose
cv::GaussianBlur(img, blur, {7,7}, 0);Gaussian smooth.
cv::medianBlur(img, med, 5);Salt-&-pepper removal.
cv::Canny(gray, edges, 50,120);Canny edge map.
cv::dilate(bin, dil, {},{-1,-1},2);Binary dilation.
cv::erode(bin, ero, {},{-1,-1},1);Erosion (shrink).
cv::adaptiveThreshold(gray, th,255,cv::ADAPTIVE_THRESH_MEAN_C,cv::THRESH_BINARY,11,2);Adaptive binarisation.

13.5 Geometric Transforms

SnippetPurpose
cv::warpAffine(img, aff, M, img.size());Apply affine M (2×3).
M = cv::getRotationMatrix2D(center, 30, 1.0);Build 2-D rotation matrix.
cv::warpPerspective(img, warp, H, dstSz);Perspective homography.
cv::remap(src, dst, mapX, mapY, cv::INTER_LINEAR);Generic pixel remap.

13.6 Features & Matching

SnippetPurpose
auto orb = cv::ORB::create();Instantiate ORB.
orb->detectAndCompute(img,{},kp,des);Keypoints & descriptors.
cv::BFMatcher(cv::NORM_HAMMING).match(des1,des2,matches);Brute-force match.
cv::drawMatches(a,kp1,b,kp2,good,out);Visualise matches.

13.7 Video & Motion

SnippetPurpose
cv::Ptr<cv::BackgroundSubtractor> bg = cv::createBackgroundSubtractorMOG2();MOG2 subtractor.
bg->apply(frame, mask);Get foreground mask.
cv::calcOpticalFlowFarneback(prev,cur,flow,0.5,3,15,3,5,1.2,0);Dense optical flow.
cv::CamShift(hist, window, termCrit);Adaptive tracking.

13.8 DNN Module

SnippetPurpose
auto net = cv::dnn::readNet("model.onnx");Load ONNX.
net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);CUDA backend.
cv::Mat blob = cv::dnn::blobFromImage(img,1/255.,{640,640},{},true,false);Build blob.
net.setInput(blob); cv::Mat out = net.forward();Run inference.
cv::dnn::NMSBoxes(boxes,scores,0.25,0.45,idx);Non-max suppression.

13.9 Useful Constants & Mat Properties

Constant / Prop.Meaning
CV_8U / CV_32FMat depth types.
img.rows / img.colsHeight / width.
img.type()Depth + #channels encoded.
cv::LINE_AAAnti-aliased draw flag.
cv::INTER_AREA / _CUBICResize interpolation enums.
cv::BORDER_REFLECT101Padding style.
VideoCapture::CAP_ANYAuto-select backend.
cv::NORM_L2 / _HAMMINGDistance metrics.