⚙️ C++ Programming Language

Quick Reference & Cheat Sheet—STL, Syntax & Standard Library

Basic Syntax

Program Structure


    #include <iostream>
    #include <vector>
    #include <string>

    using namespace std;

    int main() {
        cout << "Hello, World!" << endl;
        return 0;
    }

    // Function declaration
    int add(int a, int b);

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

Data Types

                        
// Fundamental types
bool flag = true;
char letter = 'A';
int number = 42;
float decimal = 3.14f;
double precision = 3.14159;
long long bigNumber = 1234567890LL;

// Auto keyword (C++11)
auto x = 42; // int
auto y = 3.14; // double
auto z = "hello"; // const char*

// Type aliases
using Integer = int;
typedef double Real;

// Constants
const int MAX_SIZE = 100;
constexpr double PI = 3.14159;
                        
                    

Pointers & References

                        
// Pointers
int value = 42;
int* ptr = &value; // Pointer to value
int** ptrPtr = &ptr; // Pointer to pointer

cout << *ptr << endl; // Dereference pointer

// References
int& ref = value; // Reference to value
ref = 100; // Changes value to 100

// Null pointers
int* nullPtr = nullptr; // C++11
int* oldNull = NULL; // C-style

// Smart pointers (C++11)
#include 
unique_ptr uPtr = make_unique(42);
shared_ptr sPtr = make_shared(42);
weak_ptr wPtr = sPtr;
                        
                    

STL Containers

Sequence Containers

                        
// Vector - dynamic array
vector vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.pop_back();
vec.insert(vec.begin() + 2, 10);
vec.erase(vec.begin() + 1);

// List - doubly linked list
list lst = {"apple", "banana", "cherry"};
lst.push_front("orange");
lst.push_back("grape");

// Deque - double-ended queue
deque dq = {1, 2, 3};
dq.push_front(0);
dq.push_back(4);

// Array (C++11) - fixed size
array arr = {1, 2, 3, 4, 5};
                        
                    

Associative Containers

                        
// Set - unique sorted elements
set s = {3, 1, 4, 1, 5}; // {1, 3, 4, 5}
s.insert(2);
s.erase(3);

// Map - key-value pairs
map m;
m["apple"] = 5;
m["banana"] = 3;
m.insert({"cherry", 7});

// Unordered containers (C++11)
unordered_set us = {1, 2, 3};
unordered_map um;
um["key"] = 42;
                        
                    

Container Adapters

                        
// Stack - LIFO
stack st;
st.push(1);
st.push(2);
int top = st.top();
st.pop();

// Queue - FIFO
queue q;
q.push("first");
q.push("second");
string front = q.front();
q.pop();

// Priority Queue - heap
priority_queue pq;
pq.push(3);
pq.push(1);
pq.push(4);
int max = pq.top(); // 4
                        
                    

Algorithms

Common Algorithms

sort(begin, end)
find(begin, end, value)
count(begin, end, value)
reverse(begin, end)
unique(begin, end)
binary_search(begin, end, value)
lower_bound(begin, end, value)
upper_bound(begin, end, value)
min_element(begin, end)
max_element(begin, end)
accumulate(begin, end, init)
transform(begin, end, result, op)
                        
#include 
#include 

vector vec = {3, 1, 4, 1, 5, 9, 2, 6};

// Sort
sort(vec.begin(), vec.end());

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

// Count
int count = count(vec.begin(), vec.end(), 1);

// Sum
int sum = accumulate(vec.begin(), vec.end(), 0);
                        
                    

Classes & Objects

Class Definition

                        
class Rectangle {
private:
    double width, height;

public:
    // Constructors
    Rectangle() : width(0), height(0) {}
    Rectangle(double w, double h) : width(w), height(h) {}

    // Copy constructor
    Rectangle(const Rectangle& other)
        : width(other.width), height(other.height) {}

    // Assignment operator
    Rectangle& operator=(const Rectangle& other) {
        if (this != &other) {
            width = other.width;
            height = other.height;
        }
        return *this;
    }

    // Destructor
    ~Rectangle() {}

    // Methods
    double area() const { return width * height; }
    double perimeter() const { return 2 * (width + height); }

    // Getters and setters
    double getWidth() const { return width; }
    void setWidth(double w) { width = w; }

    // Static member
    static int count;
    static void printCount() { cout << count << endl; }
};
                        
                    

Inheritance & Polymorphism

                        
// Base class
class Shape {
protected:
    string color;

public:
    Shape(const string& c) : color(c) {}
    virtual ~Shape() {} // Virtual destructor

    // Pure virtual function (abstract)
    virtual double area() const = 0;

    // Virtual function
    virtual void draw() const {
        cout << "Drawing a " << color << " shape" << endl;
    }

    // Non-virtual function
    string getColor() const { return color; }
};

// Derived class
class Circle : public Shape {
private:
    double radius;

public:
    Circle(const string& c, double r) : Shape(c), radius(r) {}

    // Override virtual function
    double area() const override {
        return 3.14159 * radius * radius;
    }

    void draw() const override {
        cout << "Drawing a " << color << " circle" << endl;
    }
};
                        
                    

Templates

Function Templates

                        
// Function template
template
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

// Template specialization
template<>
const char* maximum(const char* a, const char* b) {
    return (strcmp(a, b) > 0) ? a : b;
}

// Multiple template parameters
template
auto add(T a, U b) -> decltype(a + b) {
    return a + b;
}

// Usage
int maxInt = maximum(10, 20);
double maxDouble = maximum(3.14, 2.71);
auto result = add(5, 3.14);
                        
                    

Class Templates

                        
// Class template
template
class Stack {
private:
    vector elements;

public:
    void push(const T& element) {
        elements.push_back(element);
    }

    void pop() {
        if (!elements.empty()) {
            elements.pop_back();
        }
    }

    T top() const {
        if (!elements.empty()) {
            return elements.back();
        }
        throw runtime_error("Stack is empty");
    }

    bool empty() const {
        return elements.empty();
    }

    size_t size() const {
        return elements.size();
    }
};

// Usage
Stack intStack;
Stack stringStack;
                        
                    

Modern C++ Features

C++11/14/17 Features

                        
// Range-based for loop (C++11)
vector vec = {1, 2, 3, 4, 5};
for (const auto& element : vec) {
    cout << element << " ";
}

// Lambda expressions (C++11)
auto lambda = [](int x, int y) -> int {
    return x + y;
};

// Capture by value and reference
int multiplier = 10;
auto multiply = [multiplier](int x) { return x * multiplier; };
auto increment = [&multiplier]() { multiplier++; };

// Move semantics (C++11)
class MyClass {
public:
    // Move constructor
    MyClass(MyClass&& other) noexcept
        : data(move(other.data)) {}

    // Move assignment
    MyClass& operator=(MyClass&& other) noexcept {
        if (this != &other) {
            data = move(other.data);
        }
        return *this;
    }
};

// Uniform initialization (C++11)
vector v{1, 2, 3, 4, 5};
map m{
    {"apple", 1},
    {"banana", 2}
};

// nullptr (C++11)
int* ptr = nullptr;
                        
                    

Exception Handling

                        
// Try-catch blocks
try {
    vector vec(5);
    vec.at(10) = 42; // Throws out_of_range
} catch (const out_of_range& e) {
    cout << "Out of range error: " << e.what() << endl;
} catch (const exception& e) {
    cout << "General exception: " << e.what() << endl;
} catch (...) {
    cout << "Unknown exception" << endl;
}

// Custom exceptions
class MyException : public exception {
private:
    string message;
public:
    MyException(const string& msg) : message(msg) {}
    const char* what() const noexcept override {
        return message.c_str();
    }
};

// Throwing exceptions
void riskyFunction() {
    throw MyException("Something went wrong");
}
                        
                    
Wesley Classen
Wesley's AI Assistant Usually replies in ~15 min Ask me anything — if I can't answer, Wesley gets pinged and replies personally.
Hello! I'm Wesley's AI assistant. How can I help you today?