Built for developers, by XinhND

v2.1.0

Ready

C++ Cheat Sheet

Complete reference guide for C++ with interactive examples and live playground links

Basic Syntax

Hello World

Basic C++ program structure and output

C++
#include <iostream>

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

// Using namespace
using namespace std;
cout << "Hello, World!" << endl;

Variables and Data Types

Variable declaration and basic data types

C++
// Basic types
int number = 42;              // Integer
double pi = 3.14159;          // Double precision
float price = 19.99f;         // Single precision
char grade = 'A';             // Character
bool isActive = true;         // Boolean
string name = "C++";          // String

// Type modifiers
unsigned int positive = 42;   // Only positive
long bigNumber = 123456789L;  // Larger range
const int MAX = 100;          // Constant

// Type inference (C++11)
auto value = 42;              // int
auto text = "Hello";          // const char*
auto pi = 3.14159;            // double

// Type checking
cout << typeid(value).name(); // Get type name

String Operations

Common string operations

C++
#include <string>

string text = "Hello World";

// String methods
cout << text.length();           // 11
cout << text.size();            // 11
cout << text.substr(0, 5);      // "Hello"
cout << text.find("World");     // 6
cout << text.replace(6, 5, "C++"); // "Hello C++"

// String concatenation
string first = "Hello";
string second = "World";
string result = first + " " + second;

// String comparison
if (first == second) {
    cout << "Strings are equal";
}

// String to number
int number = stoi("42");
double pi = stod("3.14159");

Arrays and Vectors

Working with arrays and vectors

C++
#include <vector>
#include <array>

// C-style array
int numbers[5] = {1, 2, 3, 4, 5};

// Modern array (C++11)
array<int, 5> modernArray = {1, 2, 3, 4, 5};

// Vector (dynamic array)
vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);              // Add element
vec.pop_back();                // Remove last
vec.size();                    // Get size
vec.at(0);                     // Safe access
vec[0];                        // Direct access

// Vector operations
vec.insert(vec.begin(), 0);    // Insert at start
vec.erase(vec.begin());        // Remove first
vec.clear();                   // Remove all

// Range-based for loop (C++11)
for (const auto& num : vec) {
    cout << num << " ";
}

Control Structures

Control flow statements

C++
// If-else
if (age >= 18) {
    cout << "Adult";
} else if (age >= 13) {
    cout << "Teenager";
} else {
    cout << "Child";
}

// Switch
switch (status) {
    case 1:
        cout << "Active";
        break;
    case 2:
        cout << "Inactive";
        break;
    default:
        cout << "Unknown";
}

// Loops
for (int i = 0; i < 5; i++) {
    cout << i << " ";
}

while (condition) {
    // Do something
}

do {
    // Do something
} while (condition);

// Range-based for (C++11)
for (const auto& item : items) {
    cout << item << " ";
}

Functions

Function Definition

Different ways to define functions

C++
// Basic function
int add(int a, int b) {
    return a + b;
}

// Function with default parameters
void greet(string name = "World") {
    cout << "Hello, " << name << "!";
}

// Function overloading
int multiply(int a, int b) {
    return a * b;
}

double multiply(double a, double b) {
    return a * b;
}

// Inline function
inline int square(int x) {
    return x * x;
}

// Lambda function (C++11)
auto sum = [](int a, int b) { return a + b; };

Function Templates

Working with function templates

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

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

// Template specialization
template<>
string max(string a, string b) {
    return (a.length() > b.length()) ? a : b;
}

// Using templates
int result1 = max(10, 20);
double result2 = max(3.14, 2.72);
string result3 = max("Hello", "World");

Object-Oriented Programming

Classes and Objects

Basic class and object usage

C++
class Person {
private:
    string name;
    int age;

public:
    // Constructor
    Person(string n, int a) : name(n), age(a) {}
    
    // Getter methods
    string getName() const { return name; }
    int getAge() const { return age; }
    
    // Setter methods
    void setName(string n) { name = n; }
    void setAge(int a) { age = a; }
    
    // Member function
    void greet() const {
        cout << "Hello, I'm " << name << endl;
    }
};

// Creating objects
Person person("Alice", 25);
person.greet();

Inheritance and Polymorphism

Inheritance and polymorphism

C++
// Base class
class Animal {
protected:
    string name;

public:
    Animal(string n) : name(n) {}
    
    // Virtual function
    virtual void makeSound() = 0;
    
    // Virtual destructor
    virtual ~Animal() = default;
};

// Derived class
class Dog : public Animal {
public:
    Dog(string n) : Animal(n) {}
    
    // Override virtual function
    void makeSound() override {
        cout << name << " says: Woof!" << endl;
    }
};

// Using polymorphism
Animal* animal = new Dog("Buddy");
animal->makeSound();
delete animal;

Smart Pointers

Modern memory management with smart pointers

C++
#include <memory>

// Unique pointer (C++11)
unique_ptr<Person> person = make_unique<Person>("Alice", 25);

// Shared pointer (C++11)
shared_ptr<Person> person1 = make_shared<Person>("Bob", 30);
shared_ptr<Person> person2 = person1;  // Reference count: 2

// Weak pointer (C++11)
weak_ptr<Person> weakPerson = person1;

// Using smart pointers
if (person) {
    person->greet();
}

// Custom deleter
auto deleter = [](Person* p) {
    cout << "Deleting person" << endl;
    delete p;
};
unique_ptr<Person, decltype(deleter)> customPerson(
    new Person("Charlie", 35),
    deleter
);

Modern C++ Features

Move Semantics

Move semantics and rvalue references

C++
// Move constructor
class Resource {
private:
    int* data;
    
public:
    // Move constructor
    Resource(Resource&& other) noexcept
        : data(other.data) {
        other.data = nullptr;
    }
    
    // Move assignment
    Resource& operator=(Resource&& other) noexcept {
        if (this != &other) {
            delete data;
            data = other.data;
            other.data = nullptr;
        }
        return *this;
    }
};

// Using move semantics
Resource r1;
Resource r2 = std::move(r1);  // Move constructor
r1 = std::move(r2);          // Move assignment

Lambda Expressions

Working with lambda expressions

C++
// Basic lambda
auto add = [](int a, int b) { return a + b; };

// Lambda with capture
int multiplier = 10;
auto times = [multiplier](int x) { return x * multiplier; };

// Generic lambda (C++14)
auto print = [](const auto& x) { cout << x << endl; };

// Using with algorithms
vector<int> numbers = {1, 2, 3, 4, 5};
for_each(numbers.begin(), numbers.end(),
    [](int n) { cout << n << " "; }
);

// Lambda with mutable
auto counter = [count = 0]() mutable { return ++count; };

Concurrency

Modern concurrency features

C++
#include <thread>
#include <future>
#include <mutex>

// Thread creation
void task() {
    cout << "Running in thread" << endl;
}
thread t(task);
t.join();

// Async operations
auto future = async(launch::async, []() {
    return "Result from async";
});
string result = future.get();

// Mutex for synchronization
mutex mtx;
{
    lock_guard<mutex> lock(mtx);
    // Critical section
}

// Atomic operations
atomic<int> counter(0);
counter++;  // Thread-safe increment

Standard Template Library

Containers

STL container types and operations

C++
#include <vector>
#include <map>
#include <set>
#include <unordered_map>

// Vector
vector<int> vec = {1, 2, 3, 4, 5};

// Map
map<string, int> scores = {
    {"Alice", 100},
    {"Bob", 90}
};

// Set
set<int> uniqueNumbers = {1, 2, 3, 3, 4, 4, 5};

// Unordered map (hash table)
unordered_map<string, int> hashMap = {
    {"apple", 1},
    {"banana", 2}
};

// Container operations
vec.push_back(6);
scores["Charlie"] = 95;
uniqueNumbers.insert(6);
hashMap["orange"] = 3;

Algorithms

Common STL algorithms

C++
#include <algorithm>

vector<int> numbers = {5, 3, 1, 4, 2};

// Sorting
sort(numbers.begin(), numbers.end());

// Finding
auto it = find(numbers.begin(), numbers.end(), 3);

// Transforming
transform(numbers.begin(), numbers.end(),
    numbers.begin(),
    [](int n) { return n * 2; }
);

// Accumulating
int sum = accumulate(numbers.begin(), numbers.end(), 0);

// Filtering
auto it = remove_if(numbers.begin(), numbers.end(),
    [](int n) { return n % 2 == 0; }
);
numbers.erase(it, numbers.end());

C++ - Interactive Developer Reference

Hover over code blocks to copy or run in live playground