Cpp
C++ Cheatsheet
Basic Structure
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
Data Types
int x = 5; // Integer
float f = 3.14f; // Floating point
double d = 3.14159; // Double precision
char c = 'A'; // Character
bool b = true; // Boolean
string s = "Hello"; // String (requires #include <string>)
auto a = 10; // Auto type deduction
cout << "Output" << endl; // Output
cin >> variable; // Input
printf("Format %d", value); // C-style output
scanf("%d", &variable); // C-style input
Operators
// Arithmetic: +, -, *, /, %, ++, --
// Comparison: ==, !=, <, >, <=, >=
// Logical: &&, ||, !
// Bitwise: &, |, ^, ~, <<, >>
// Assignment: =, +=, -=, *=, /=, %=
Control Structures
// If-Else
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}
// Switch
switch(variable) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}
// Ternary
result = (condition) ? value1 : value2;
Loops
// For loop
for (int i = 0; i < 10; i++) {
// code
}
// While loop
while (condition) {
// code
}
// Do-While loop
do {
// code
} while (condition);
// Range-based for loop (C++11)
for (auto element : container) {
// code
}
Functions
// Function declaration
int add(int a, int b);
// Function definition
int add(int a, int b) {
return a + b;
}
// Function with default parameters
void display(int x = 10);
// Function overloading
int add(int a, int b);
double add(double a, double b);
// Lambda functions (C++11)
auto lambda = [](int x) { return x * 2; };
Arrays
int arr[5] = {1, 2, 3, 4, 5};
int matrix[3][3];
arr[0] = 10; // Access element
Pointers
int* ptr; // Pointer declaration
ptr = &variable; // Address-of operator
int value = *ptr; // Dereference operator
int* arr = new int[10]; // Dynamic allocation
delete[] arr; // Deallocation
References
int& ref = variable; // Reference
void swap(int& a, int& b); // Pass by reference
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 creation
MyClass* ptr = new MyClass(); // Dynamic object
delete ptr;
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
#include <string>
string s = "Hello";
s.length();
s.substr(0, 3);
s.find("ll");
s.append(" World");
s + " World";
s.compare("Hello");
Memory Management
int* p = new int; // Allocate
delete p; // Deallocate
int* arr = new int[10]; // Array allocation
delete[] arr; // Array deallocation
unique_ptr<int> up(new int); // Smart pointer (C++11)
shared_ptr<int> sp = make_shared<int>(10);
Exception Handling
try {
// code
throw exception("Error");
} catch (exception& e) {
cout << e.what() << endl;
} catch (...) {
// catch all
}
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
#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
#include <header>
#define PI 3.14159
#ifdef MACRO
#ifndef MACRO
#endif
Type Casting
// C-style cast
int x = (int)3.14;
// C++ style casts
static_cast<int>(3.14); // Compile-time cast
dynamic_cast<Derived*>(basePtr); // Runtime cast (polymorphic types)
const_cast<int*>(constPtr); // Remove const
reinterpret_cast<int*>(ptr); // Low-level reinterpret
Namespace
namespace MyNamespace {
int value = 10;
void function() {}
}
using namespace MyNamespace;
using MyNamespace::value;
MyNamespace::function();
namespace alias = MyNamespace;
Enum
// Traditional enum
enum Color { RED, GREEN, BLUE };
Color c = RED;
// Enum class (C++11) - strongly typed
enum class Status { Active, Inactive, Pending };
Status s = Status::Active;
Struct
struct Point {
int x, y;
Point(int a, int b) : x(a), y(b) {}
};
Point p = {10, 20};
Point p2(10, 20);
Union
union Data {
int i;
float f;
char c;
};
Data d;
d.i = 10;
Typedef & Using
typedef unsigned long ulong;
typedef int* IntPtr;
using ulong = unsigned long; // C++11 alias
using IntPtr = int*;
Templates
// Function template
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template <class T>
class Container {
T element;
public:
void set(T arg) { element = arg; }
T get() { return element; }
};
// Template specialization
template <>
class Container<char> {
// specialized implementation
};
// Variadic templates (C++11)
template<typename... Args>
void print(Args... args);
Inheritance
class Base {
protected:
int value;
public:
virtual void display() {}
virtual ~Base() {}
};
// Single inheritance
class Derived : public Base {
public:
void display() override {}
};
// Multiple inheritance
class Multi : public Base1, public Base2 {};
// Access specifiers: public, protected, private
Polymorphism
// Virtual functions
class 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 override
void show() override;
void show() final; // Cannot be overridden further
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
class MyClass {
int private_data;
friend void friendFunction(MyClass& obj);
friend class FriendClass;
};
Static Members
class Counter {
static int count;
public:
static int getCount() { return count; }
};
int Counter::count = 0; // Definition
Const & Constexpr
const int x = 10;
const int* ptr; // Pointer to const
int* const ptr; // Const pointer
const 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 function
Inline Functions
inline int square(int x) {
return x * x;
}
Function Pointers
int (*funcPtr)(int, int);
funcPtr = &add;
int result = (*funcPtr)(5, 3);
int result = funcPtr(5, 3); // Also valid
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 operations
advance(it, 3);
distance(it1, it2);
next(it);
prev(it);
STL Algorithms (Extended)
#include <algorithm>
#include <numeric>
// Searching
binary_search(v.begin(), v.end(), value);
lower_bound(v.begin(), v.end(), value);
upper_bound(v.begin(), v.end(), value);
// Modifying
copy(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);
// Numeric
accumulate(v.begin(), v.end(), 0);
inner_product(v1.begin(), v1.end(), v2.begin(), 0);
partial_sum(v.begin(), v.end(), result.begin());
// Partitioning
partition(v.begin(), v.end(), predicate);
// Set operations
set_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/Max
min(a, b);
max(a, b);
minmax(a, b); // Returns pair
clamp(value, low, high); // C++17
Lambda Expressions (C++11)
// Basic lambda
auto lambda = []() { cout << "Hello"; };
// Lambda with parameters
auto add = [](int a, int b) { return a + b; };
// Lambda with capture
int 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 lambda
auto mut = [x]() mutable { x++; return x; };
// Lambda with return type
auto explicit_return = [](int x) -> double { return x * 1.5; };
Move Semantics (C++11)
// Rvalue references
int&& rref = 10;
// Move constructor
MyClass(MyClass&& other) noexcept;
// Move assignment
MyClass& operator=(MyClass&& other) noexcept;
// std::move
vector<int> v1 = {1, 2, 3};
vector<int> v2 = std::move(v1); // v1 is now empty
// Perfect forwarding
template<typename T>
void wrapper(T&& arg) {
func(std::forward<T>(arg));
}
Smart Pointers (C++11)
#include <memory>
// unique_ptr - exclusive ownership
unique_ptr<int> up1(new int(5));
unique_ptr<int> up2 = make_unique<int>(10); // C++14
unique_ptr<int> up3 = std::move(up2);
// shared_ptr - shared ownership
shared_ptr<int> sp1 = make_shared<int>(5);
shared_ptr<int> sp2 = sp1; // Reference count = 2
sp1.use_count();
sp1.reset();
// weak_ptr - non-owning reference
weak_ptr<int> wp = sp1;
if (auto sp = wp.lock()) {
// Use sp
}
Multithreading (C++11)
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
// Thread
void function() {}
thread t1(function);
thread t2([]() { cout << "Lambda thread"; });
t1.join();
t2.detach();
// Mutex
mutex mtx;
mtx.lock();
// critical section
mtx.unlock();
// Lock guard
{
lock_guard<mutex> lock(mtx);
// auto unlock when out of scope
}
// Unique lock
unique_lock<mutex> lock(mtx);
lock.unlock();
lock.lock();
// Atomic
atomic<int> counter(0);
counter++;
counter.fetch_add(1);
Chrono Library (C++11)
#include <chrono>
auto start = chrono::high_resolution_clock::now();
// code
auto 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)
#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)
#include <regex>
regex pattern("\\\\d+");
string text = "123 abc 456";
// Match
if (regex_match(text, pattern)) {}
// Search
smatch matches;
if (regex_search(text, matches, pattern)) {
cout << matches[0];
}
// Replace
string result = regex_replace(text, pattern, "X");
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)
#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)
#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+)
[[noreturn]] void terminate();
[[deprecated]] void old_function();
[[nodiscard]] int important();
[[maybe_unused]] int x;
[[fallthrough]] // In switch statement
Assert & Static Assert
#include <cassert>
assert(x > 0); // Runtime assertion
static_assert(sizeof(int) == 4, "Ints must be 4 bytes"); // Compile-time