// value initialization
int i{}; // 0
double d{3.14}; // brace (uniform) init – avoids narrowing
auto name = "Ada"; // type deduced as const char*
auto
deduces most types, use auto*
or auto&
to deduce ptr/ref.decltype(expr)
yields the type of expr.constexpr
variables are evaluated at compile-time when possible.using
namespace math::geometry {
double tau() { return 6.283; }
}
using math::geometry::tau; // selective
using namespace std::string_literals; // literal suffixes
<iostream>
)#include <iostream>
int main(){
std::cout << "enter age: ";
int age{};
if (std::cin >> age){
std::cout << "in months: " << age*12 << '\n';
}
}
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";
}
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
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);
[[nodiscard]] int add(int a, int b = 0){ return a + b; }
[[nodiscard]]
warns if result is ignored.double area(double r); // circle
double area(double w, double h); // rectangle
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; };
template<std::integral I>
auto gcd(I a, I b) -> I { … }
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_); }
};
~T()
– destructorT(const T&)
, T& operator=(const T&)
T(T&&)
, T& operator=(T&&)
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; }
};
std::unique_ptr<Shape> s = std::make_unique<Circle>(2.0);
std::cout << s->area(); // dynamic dispatch
template<typename T>
T max(T a, T b){ return (a > b) ? a : b; }
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; }
};
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>;
template<typename... Ts>
auto sum(Ts... xs){ return (xs + ... ); }
std::vector
– contiguous, fast push_back/iteration.std::deque
– double-ended queue.std::list
, std::forward_list
.std::map / std::unordered_map
.std::vector<int> a{1,2,3};
a.push_back(4); // O(1) amortized
for (auto n : a) std::cout << n;
<algorithm>
)std::ranges::sort(a); // C++20 ranges
auto pos = std::ranges::find(a, 3);
std::ranges::transform(a, a.begin(), square);
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;
#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();
auto sp = std::make_shared<Widget>(); // shared ownership
auto up = std::make_unique<Widget>(); // exclusive
std::weak_ptr<Widget> wp = sp; // non-owning
new
& delete
Use std::make_unique/make_shared
instead of raw new
. Direct delete
is error-prone.
std::lock_guard lg{mtx}; // locks in ctor, unlocks in dtor
try {
if(!file) throw std::runtime_error("cannot closed");
} catch(const std::exception& ex){
std::cerr << ex.what();
}
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(); }
std::thread
std::thread t([]{
heavy_task();
});
t.join();
auto fut = std::async(std::launch::async, compute);
std::cout << fut.get();
std::atomic<int> counter{};
std::mutex mtx;
task<void> run(){
for(int i=0;i<3;++i){
co_await sleep_for(1s);
std::cout << i;
}
}
// file: math.ixx
export module math;
export int add(int a,int b){ return a+b; }
import math;
int v = math::add(1,2);
Modules speed-up builds and improve encapsulation compared to headers.
g++
& clang++
g++ -std=c++23 -O2 -Wall main.cpp -o main
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)
std::string s = std::to_string(num);
std::erase_if(vec, pred);
(C++20) – remove by predicate.std::clamp(x, lo, hi);
std::views::iota(0,10)
– lazy range.:: .* ->* // scope / ptr-to-member
++ -- () [] // postfix
++ -- + - ! ~ // unary
* / % // multiplicative
+ - // additive
<< >> // shifts
< ≤ > ≥ // relational
== != // equality
& // bitwise AND
^ // XOR
| // OR
&& // logical AND
|| // logical OR
?: // conditional
= += … // assignment
, // comma
alignas, concept, constexpr, co_await, delete, export,
explicit, friend, inline, mutable, noexcept, override,
requires, static_cast, thread_local, typename, volatile …
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).
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Snippet | Purpose |
---|---|
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. |
Constant / Prop. | Meaning |
---|---|
CV_8U / CV_32F | Mat depth types. |
img.rows / img.cols | Height / width. |
img.type() | Depth + #channels encoded. |
cv::LINE_AA | Anti-aliased draw flag. |
cv::INTER_AREA / _CUBIC | Resize interpolation enums. |
cv::BORDER_REFLECT101 | Padding style. |
VideoCapture::CAP_ANY | Auto-select backend. |
cv::NORM_L2 / _HAMMING | Distance metrics. |