ENGIMY.IO - CHEATSHEET
C++ × QUICK REFERENCE
REFERENCE vC++17/20

C++ Quick Reference

Everything you need day‑to‑day – syntax, examples, and modern C++ features.

Data Types

Fundamental Types
  • int4 bytes
  • char1 byte
  • booltrue/false
  • float4 bytes
  • double8 bytes
  • voidno value
  • autotype deduction
  • decltypetype of expression
Derived Types
  • arrayfixed‑size container
  • vectordynamic array
  • stringtext
  • pairtwo values
  • tuplemultiple values
  • optionalmay contain value
  • varianttype‑safe union
  • anyany type

Type Aliases

// using (preferred)
using int_ptr = int*;
using VecInt = std::vector<int>;

// typedef (legacy)
typedef int* int_ptr;
typedef std::vector<int> VecInt;

Variables

// Declaration and initialisation
int age = 25;
double pi = 3.14159;
char grade = 'A';
std::string name = "Alice";
bool is_active = true;
const double TAX_RATE = 0.08;

// Type deduction
auto x = 42;           // int
auto y = 3.14;         // double
auto z = "hello";      // const char*
auto s = std::string("world"); // std::string

// Modern initialisation
int a{42};
std::vector<int> v{1, 2, 3, 4};

Control Flow

if / else if / else

if (x > 0) {
    std::cout << "positive" << std::endl;
} else if (x == 0) {
    std::cout << "zero" << std::endl;
} else {
    std::cout << "negative" << std::endl;
}

switch

switch (grade) {
    case 'A':
        std::cout << "Excellent" << std::endl;
        break;
    case 'B':
        std::cout << "Good" << std::endl;
        break;
    default:
        std::cout << "Keep trying" << std::endl;
}

Loops

// for loop
for (int i = 0; i < 10; i++) {
    std::cout << i << " ";
}

// Range‑based for (C++11)
std::vector<int> nums = {1, 2, 3, 4, 5};
for (int n : nums) {
    std::cout << n << " ";
}

// with auto & reference
for (auto& n : nums) {
    n *= 2;  // modifies original
}

// while loop
int i = 0;
while (i < 10) {
    std::cout << i++ << " ";
}

// do‑while loop
int i = 0;
do {
    std::cout << i++ << " ";
} while (i < 10);

Functions

Declaration & Definition

// Prototype
int add(int a, int b);

// Definition
int add(int a, int b) {
    return a + b;
}

// Default arguments
void greet(const std::string& name, const std::string& greeting = "Hello") {
    std::cout << greeting << ", " << name << std::endl;
}

// Function overloading
int max(int a, int b) { return (a > b) ? a : b; }
double max(double a, double b) { return (a > b) ? a : b; }

// Lambda expressions (C++11)
auto square = [](int x) { return x * x; };
int result = square(5);  // 25

Lambdas in Detail

// Capture by value
int x = 10;
auto f = [x]() { return x; };

// Capture by reference
auto g = [&x]() { x += 1; };

// Capture all by value
auto h = [=]() { return x; };

// Capture all by reference
auto j = [&]() { x += 1; };

// Mutable lambda
auto k = [x]() mutable { x += 1; return x; };

Classes & Objects

Basic Class

class Person {
private:
    std::string name_;
    int age_;

public:
    // Constructor
    Person(const std::string& name, int age)
        : name_(name), age_(age) {}

    // Default constructor
    Person() : name_(""), age_(0) {}

    // Member functions
    void introduce() const {
        std::cout << "I am " << name_ << ", " << age_ << " years old" << std::endl;
    }

    // Getters / Setters
    std::string getName() const { return name_; }
    void setName(const std::string& name) { name_ = name; }
};

Constructors & Destructors

// Constructor with initialiser list
class Student : public Person {
private:
    int roll_no_;

public:
    Student(const std::string& name, int age, int roll_no)
        : Person(name, age), roll_no_(roll_no) {}

    // Destructor
    ~Student() {
        std::cout << "Student destroyed" << std::endl;
    }
};

Inheritance

// Base class
class Shape {
protected:
    double width_;
    double height_;

public:
    Shape(double w, double h) : width_(w), height_(h) {}
    virtual double area() const = 0;  // pure virtual
    virtual ~Shape() = default;
};

// Derived class
class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : Shape(w, h) {}
    double area() const override {
        return width_ * height_;
    }
};

// Use
Rectangle rect(5, 10);
double a = rect.area();  // 50

Templates

Function Templates

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

// Usage
int m1 = max(10, 20);      // int
double m2 = max(3.14, 2.7); // double

Class Templates

template<typename T>
class Box {
private:
    T content_;
public:
    Box(const T& content) : content_(content) {}
    T get() const { return content_; }
};

// Usage
Box<int> intBox(42);
Box<std::string> strBox("hello");

STL Containers

Sequence Containers
  • std::vector<T>dynamic array
  • std::deque<T>double‑ended queue
  • std::list<T>doubly‑linked list
  • std::forward_list<T>singly‑linked list
  • std::array<T, N>fixed‑size array
  • std::stringtext
Associative Containers
  • std::set<T>unique keys (sorted)
  • std::map<K, V>key‑value (sorted)
  • std::unordered_set<T>unique keys (hash)
  • std::unordered_map<K, V>key‑value (hash)
  • std::multiset<T>non‑unique keys
  • std::multimap<K, V>non‑unique key‑value

Vector Operations

std::vector<int> v = {1, 2, 3, 4};

v.push_back(5);          // add to end
v.pop_back();            // remove last
v.insert(v.begin() + 2, 99); // insert at position
v.erase(v.begin() + 1);  // remove at position
v.size();                // number of elements
v.empty();               // check if empty
v.clear();               // remove all

// Access
int x = v[0];            // no bounds check
int y = v.at(0);         // bounds check (throws)
int z = v.front();       // first element
int w = v.back();        // last element

Map Operations

std::map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;

// Iterate
for (const auto& [name, score] : scores) {
    std::cout << name << ": " << score << std::endl;
}

// Find
auto it = scores.find("Alice");
if (it != scores.end()) {
    std::cout << "Found: " << it->second << std::endl;
}

Smart Pointers

// unique_ptr – exclusive ownership
std::unique_ptr<int> p1 = std::make_unique<int>(42);
std::unique_ptr<int> p2 = std::move(p1);  // transfer ownership

// shared_ptr – shared ownership
std::shared_ptr<int> sp1 = std::make_shared<int>(100);
std::shared_ptr<int> sp2 = sp1;  // reference count = 2

// weak_ptr – non‑owning observer
std::weak_ptr<int> wp = sp1;
if (auto locked = wp.lock()) {
    std::cout << *locked << std::endl;  // 100
}

// Custom deleter
std::unique_ptr<FILE, decltype(&fclose)> file(fopen("file.txt", "r"), &fclose);

Exception Handling

try {
    int result = 10 / 0;  // throws
} catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
} catch (...) {
    std::cerr << "Unknown error" << std::endl;
}

// Throwing
if (age < 0) {
    throw std::invalid_argument("Age cannot be negative");
}

// Custom exception
class MyException : public std::exception {
    const char* what() const noexcept override {
        return "Custom exception";
    }
};

File I/O (fstream)

// Write to file
std::ofstream out("file.txt");
if (out.is_open()) {
    out << "Hello, World!" << std::endl;
    out.close();
}

// Read from file
std::ifstream in("file.txt");
std::string line;
if (in.is_open()) {
    while (std::getline(in, line)) {
        std::cout << line << std::endl;
    }
    in.close();
}

// Append to file
std::ofstream append("file.txt", std::ios::app);
append << "Appended line" << std::endl;

Common STL Algorithms

//  header
std::vector<int> v = {5, 2, 8, 1, 9};

std::sort(v.begin(), v.end());          // {1, 2, 5, 8, 9}
std::reverse(v.begin(), v.end());       // {9, 8, 5, 2, 1}

auto it = std::find(v.begin(), v.end(), 5);  // find 5
if (it != v.end()) {
    std::cout << "Found at: " << std::distance(v.begin(), it) << std::endl;
}

// Transform (map)
std::vector<int> squares;
std::transform(v.begin(), v.end(), std::back_inserter(squares),
               [](int x) { return x * x; });

// Count
int count = std::count_if(v.begin(), v.end(), [](int x) { return x > 5; });

// Copy
std::vector<int> dest;
std::copy(v.begin(), v.end(), std::back_inserter(dest));

Ranges (C++20)

// Need C++20 and 
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};

// Filter and transform
auto result = v | std::views::filter([](int x) { return x % 2 == 0; })
                 | std::views::transform([](int x) { return x * x; });

for (int n : result) {
    std::cout << n << " ";  // 4, 16, 36, 64
}

// Take / Drop
for (int n : v | std::views::take(3)) {  // 1, 2, 3
    std::cout << n << " ";
}

Modern C++ Tips

  • Use auto to reduce verbosity and improve maintainability.
  • Prefer std::array over C‑style arrays.
  • Use nullptr instead of NULL or 0.
  • Mark functions noexcept when they don't throw.
  • Use constexpr for compile‑time evaluation.
  • Prefer std::unique_ptr over raw pointers for ownership.
  • Use std::move to transfer ownership efficiently.
  • Use structured bindings for tuples and pairs.
  • Prefer using over typedef.
  • Use override and final keywords.
📌 Quick Reference
Check your C++ version: g++ --version
Compile with C++17: g++ -std=c++17 program.cpp -o program
Compile with all warnings: g++ -Wall -Wextra -pedantic program.cpp -o program
Run with sanitizers (debug): g++ -fsanitize=address -g program.cpp -o program
← Back to All Cheatsheets