C++ Quick Reference
Everything you need day‑to‑day – syntax, examples, and modern C++ features.
Data Types
Fundamental Types
int– 4 byteschar– 1 bytebool– true/falsefloat– 4 bytesdouble– 8 bytesvoid– no valueauto– type deductiondecltype– type of expression
Derived Types
array– fixed‑size containervector– dynamic arraystring– textpair– two valuestuple– multiple valuesoptional– may contain valuevariant– type‑safe unionany– any 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 arraystd::deque<T>– double‑ended queuestd::list<T>– doubly‑linked liststd::forward_list<T>– singly‑linked liststd::array<T, N>– fixed‑size arraystd::string– text
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 keysstd::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 andstd::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
autoto reduce verbosity and improve maintainability. - Prefer
std::arrayover C‑style arrays. - Use
nullptrinstead ofNULLor0. - Mark functions
noexceptwhen they don't throw. - Use
constexprfor compile‑time evaluation. - Prefer
std::unique_ptrover raw pointers for ownership. - Use
std::moveto transfer ownership efficiently. - Use structured bindings for tuples and pairs.
- Prefer
usingovertypedef. - Use
overrideandfinalkeywords.
📌 Quick Reference
Check your C++ version:
Compile with C++17:
Compile with all warnings:
Run with sanitizers (debug):
g++ --versionCompile with C++17:
g++ -std=c++17 program.cpp -o programCompile with all warnings:
g++ -Wall -Wextra -pedantic program.cpp -o programRun with sanitizers (debug):
g++ -fsanitize=address -g program.cpp -o program