C++ Cheatsheet
Section titled “C++ Cheatsheet”Basic Structure
Section titled “Basic Structure”#include <iostream>using namespace std;
int main() { cout << "Hello World!" << endl; return 0;}Data Types
Section titled “Data Types”int x = 5; // Integerfloat f = 3.14f; // Floating pointdouble d = 3.14159; // Double precisionchar c = 'A'; // Characterbool b = true; // Booleanstring s = "Hello"; // String (requires #include <string>)auto a = 10; // Auto type deductionInput/Output
Section titled “Input/Output”cout << "Output" << endl; // Outputcin >> variable; // Inputprintf("Format %d", value); // C-style outputscanf("%d", &variable); // C-style inputOperators
Section titled “Operators”// Arithmetic: +, -, *, /, %, ++, --// Comparison: ==, !=, <, >, <=, >=// Logical: &&, ||, !// Bitwise: &, |, ^, ~, <<, >>// Assignment: =, +=, -=, *=, /=, %=Control Structures
Section titled “Control Structures”// If-Elseif (condition) { // code} else if (condition2) { // code} else { // code}
// Switchswitch(variable) { case 1: // code break; case 2: // code break; default: // code}
// Ternaryresult = (condition) ? value1 : value2;// For loopfor (int i = 0; i < 10; i++) { // code}
// While loopwhile (condition) { // code}
// Do-While loopdo { // code} while (condition);
// Range-based for loop (C++11)for (auto element : container) { // code}Functions
Section titled “Functions”// Function declarationint add(int a, int b);
// Function definitionint add(int a, int b) { return a + b;}
// Function with default parametersvoid display(int x = 10);
// Function overloadingint add(int a, int b);double add(double a, double b);
// Lambda functions (C++11)auto lambda = [](int x) { return x * 2; };Arrays
Section titled “Arrays”int arr[5] = {1, 2, 3, 4, 5};int matrix[3][3];arr[0] = 10; // Access elementPointers
Section titled “Pointers”int* ptr; // Pointer declarationptr = &variable; // Address-of operatorint value = *ptr; // Dereference operatorint* arr = new int[10]; // Dynamic allocationdelete[] arr; // DeallocationReferences
Section titled “References”int& ref = variable; // Referencevoid swap(int& a, int& b); // Pass by referenceClasses & Objects
Section titled “Classes & Objects”class MyClass {private: int x;public: MyClass(); // Constructor ~MyClass(); // Destructor void method(); // Method static int count; // Static member virtual void func(); // Virtual function};
MyClass obj; // Object creationMyClass* ptr = new MyClass(); // Dynamic objectdelete ptr;STL Containers
Section titled “STL Containers”#include <vector>#include <list>#include <map>#include <set>#include <queue>#include <stack>
vector<int> v = {1, 2, 3};v.push_back(4);v.pop_back();v.size();
map<string, int> m;m["key"] = value;
set<int> s = {1, 2, 3};String Operations
Section titled “String Operations”#include <string>
string s = "Hello";s.length();s.substr(0, 3);s.find("ll");s.append(" World");s + " World";s.compare("Hello");Memory Management
Section titled “Memory Management”int* p = new int; // Allocatedelete p; // Deallocate
int* arr = new int[10]; // Array allocationdelete[] arr; // Array deallocation
unique_ptr<int> up(new int); // Smart pointer (C++11)shared_ptr<int> sp = make_shared<int>(10);Exception Handling
Section titled “Exception Handling”try { // code throw exception("Error");} catch (exception& e) { cout << e.what() << endl;} catch (...) { // catch all}File I/O
Section titled “File I/O”#include <fstream>
ofstream outFile("file.txt");outFile << "Data" << endl;outFile.close();
ifstream inFile("file.txt");string line;getline(inFile, line);inFile.close();Common Algorithms
Section titled “Common Algorithms”#include <algorithm>
sort(v.begin(), v.end());reverse(v.begin(), v.end());find(v.begin(), v.end(), value);count(v.begin(), v.end(), value);max_element(v.begin(), v.end());min_element(v.begin(), v.end());Preprocessor Directives
Section titled “Preprocessor Directives”#include <header>#define PI 3.14159#ifdef MACRO#ifndef MACRO#endifType Casting
Section titled “Type Casting”// C-style castint x = (int)3.14;
// C++ style castsstatic_cast<int>(3.14); // Compile-time castdynamic_cast<Derived*>(basePtr); // Runtime cast (polymorphic types)const_cast<int*>(constPtr); // Remove constreinterpret_cast<int*>(ptr); // Low-level reinterpretNamespace
Section titled “Namespace”namespace MyNamespace { int value = 10; void function() {}}
using namespace MyNamespace;using MyNamespace::value;MyNamespace::function();
namespace alias = MyNamespace;// Traditional enumenum Color { RED, GREEN, BLUE };Color c = RED;
// Enum class (C++11) - strongly typedenum class Status { Active, Inactive, Pending };Status s = Status::Active;Struct
Section titled “Struct”struct Point { int x, y; Point(int a, int b) : x(a), y(b) {}};
Point p = {10, 20};Point p2(10, 20);union Data { int i; float f; char c;};
Data d;d.i = 10;Typedef & Using
Section titled “Typedef & Using”typedef unsigned long ulong;typedef int* IntPtr;
using ulong = unsigned long; // C++11 aliasusing IntPtr = int*;Templates
Section titled “Templates”// Function templatetemplate <typename T>T max(T a, T b) { return (a > b) ? a : b;}
// Class templatetemplate <class T>class Container { T element;public: void set(T arg) { element = arg; } T get() { return element; }};
// Template specializationtemplate <>class Container<char> { // specialized implementation};
// Variadic templates (C++11)template<typename... Args>void print(Args... args);Inheritance
Section titled “Inheritance”class Base {protected: int value;public: virtual void display() {} virtual ~Base() {}};
// Single inheritanceclass Derived : public Base {public: void display() override {}};
// Multiple inheritanceclass Multi : public Base1, public Base2 {};
// Access specifiers: public, protected, privatePolymorphism
Section titled “Polymorphism”// Virtual functionsclass Base {public: virtual void show() { cout << "Base"; } virtual void pure() = 0; // Pure virtual (abstract)};
class Derived : public Base {public: void show() override { cout << "Derived"; } void pure() override {}};
// Function overridevoid show() override;void show() final; // Cannot be overridden furtherOperator Overloading
Section titled “Operator Overloading”class Complex { double real, imag;public: Complex operator+(const Complex& c) { return Complex(real + c.real, imag + c.imag); }
Complex operator++(); // Prefix Complex operator++(int); // Postfix
friend ostream& operator<<(ostream& os, const Complex& c);
bool operator==(const Complex& c); Complex& operator=(const Complex& c); double operator[](int index);};Friend Functions & Classes
Section titled “Friend Functions & Classes”class MyClass { int private_data; friend void friendFunction(MyClass& obj); friend class FriendClass;};Static Members
Section titled “Static Members”class Counter { static int count;public: static int getCount() { return count; }};
int Counter::count = 0; // DefinitionConst & Constexpr
Section titled “Const & Constexpr”const int x = 10;const int* ptr; // Pointer to constint* const ptr; // Const pointerconst int* const ptr; // Const pointer to const
constexpr int factorial(int n) { // C++11 return (n <= 1) ? 1 : n * factorial(n - 1);}
const int& getRef() const; // Const member functionInline Functions
Section titled “Inline Functions”inline int square(int x) { return x * x;}Function Pointers
Section titled “Function Pointers”int (*funcPtr)(int, int);funcPtr = &add;int result = (*funcPtr)(5, 3);int result = funcPtr(5, 3); // Also validSTL Iterators
Section titled “STL Iterators”vector<int>::iterator it;vector<int>::const_iterator cit;vector<int>::reverse_iterator rit;
for (it = v.begin(); it != v.end(); ++it) { cout << *it;}
// Iterator operationsadvance(it, 3);distance(it1, it2);next(it);prev(it);STL Algorithms (Extended)
Section titled “STL Algorithms (Extended)”#include <algorithm>#include <numeric>
// Searchingbinary_search(v.begin(), v.end(), value);lower_bound(v.begin(), v.end(), value);upper_bound(v.begin(), v.end(), value);
// Modifyingcopy(v1.begin(), v1.end(), v2.begin());fill(v.begin(), v.end(), value);replace(v.begin(), v.end(), old_val, new_val);remove(v.begin(), v.end(), value);unique(v.begin(), v.end());transform(v.begin(), v.end(), v2.begin(), func);
// Numericaccumulate(v.begin(), v.end(), 0);inner_product(v1.begin(), v1.end(), v2.begin(), 0);partial_sum(v.begin(), v.end(), result.begin());
// Partitioningpartition(v.begin(), v.end(), predicate);
// Set operationsset_union(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
// Min/Maxmin(a, b);max(a, b);minmax(a, b); // Returns pairclamp(value, low, high); // C++17Lambda Expressions (C++11)
Section titled “Lambda Expressions (C++11)”// Basic lambdaauto lambda = []() { cout << "Hello"; };
// Lambda with parametersauto add = [](int a, int b) { return a + b; };
// Lambda with captureint x = 10;auto capture_by_value = [x]() { return x; };auto capture_by_ref = [&x]() { x++; };auto capture_all_by_value = [=]() { return x; };auto capture_all_by_ref = [&]() { x++; };auto mixed = [x, &y]() { return x + y; };
// Mutable lambdaauto mut = [x]() mutable { x++; return x; };
// Lambda with return typeauto explicit_return = [](int x) -> double { return x * 1.5; };Move Semantics (C++11)
Section titled “Move Semantics (C++11)”// Rvalue referencesint&& rref = 10;
// Move constructorMyClass(MyClass&& other) noexcept;
// Move assignmentMyClass& operator=(MyClass&& other) noexcept;
// std::movevector<int> v1 = {1, 2, 3};vector<int> v2 = std::move(v1); // v1 is now empty
// Perfect forwardingtemplate<typename T>void wrapper(T&& arg) { func(std::forward<T>(arg));}Smart Pointers (C++11)
Section titled “Smart Pointers (C++11)”#include <memory>
// unique_ptr - exclusive ownershipunique_ptr<int> up1(new int(5));unique_ptr<int> up2 = make_unique<int>(10); // C++14unique_ptr<int> up3 = std::move(up2);
// shared_ptr - shared ownershipshared_ptr<int> sp1 = make_shared<int>(5);shared_ptr<int> sp2 = sp1; // Reference count = 2sp1.use_count();sp1.reset();
// weak_ptr - non-owning referenceweak_ptr<int> wp = sp1;if (auto sp = wp.lock()) { // Use sp}Multithreading (C++11)
Section titled “Multithreading (C++11)”#include <thread>#include <mutex>#include <condition_variable>#include <atomic>
// Threadvoid function() {}thread t1(function);thread t2([]() { cout << "Lambda thread"; });t1.join();t2.detach();
// Mutexmutex mtx;mtx.lock();// critical sectionmtx.unlock();
// Lock guard{ lock_guard<mutex> lock(mtx); // auto unlock when out of scope}
// Unique lockunique_lock<mutex> lock(mtx);lock.unlock();lock.lock();
// Atomicatomic<int> counter(0);counter++;counter.fetch_add(1);Chrono Library (C++11)
Section titled “Chrono Library (C++11)”#include <chrono>
auto start = chrono::high_resolution_clock::now();// codeauto end = chrono::high_resolution_clock::now();auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);
this_thread::sleep_for(chrono::seconds(1));Random Numbers (C++11)
Section titled “Random Numbers (C++11)”#include <random>
random_device rd;mt19937 gen(rd());uniform_int_distribution<> dis(1, 6);int random_num = dis(gen);
normal_distribution<> normal(0, 1);uniform_real_distribution<> real(0.0, 1.0);Regex (C++11)
Section titled “Regex (C++11)”#include <regex>
regex pattern("\\\\d+");string text = "123 abc 456";
// Matchif (regex_match(text, pattern)) {}
// Searchsmatch matches;if (regex_search(text, matches, pattern)) { cout << matches[0];}
// Replacestring result = regex_replace(text, pattern, "X");Tuple (C++11)
Section titled “Tuple (C++11)”#include <tuple>
tuple<int, string, double> t(1, "hello", 3.14);auto t2 = make_tuple(1, "hello", 3.14);
int x = get<0>(t);string s = get<1>(t);
tie(x, s, ignore) = t; // Unpack
// Structured binding (C++17)auto [a, b, c] = t;Optional (C++17)
Section titled “Optional (C++17)”#include <optional>
optional<int> maybe_value;optional<int> has_value = 42;
if (has_value) { cout << *has_value;}
int val = has_value.value_or(0);Variant (C++17)
Section titled “Variant (C++17)”#include <variant>
variant<int, string, double> v;v = 42;v = "hello";
int i = get<int>(v);if (holds_alternative<string>(v)) { string s = get<string>(v);}Attributes (C++11+)
Section titled “Attributes (C++11+)”[[noreturn]] void terminate();[[deprecated]] void old_function();[[nodiscard]] int important();[[maybe_unused]] int x;[[fallthrough]] // In switch statementAssert & Static Assert
Section titled “Assert & Static Assert”#include <cassert>
assert(x > 0); // Runtime assertion
static_assert(sizeof(int) == 4, "Ints must be 4 bytes"); // Compile-time