Menu

C++ Cheat Sheet

Last updated

Hello World & program structure

Execution starts at main, which returns an int.

ElementCode
Include a header#include <iostream>
Entry pointint main() { ... }
Print a linestd::cout << "Hello, World!" << std::endl;
Read inputstd::cin >> x;
Use the std namespaceusing namespace std;
Return successreturn 0;
Comments// line and /* block */

Data types

TypeDescription
intInteger (usually 32 bits)
long / long longWider integers
float / doubleFloating point numbers
charSingle byte / character
booltrue or false
std::stringDynamic text from <string>
autoCompiler infers the type
std::size_tUnsigned type for sizes and indices

Variables & references

References are aliases; pointers hold addresses.

OperationSyntax
Declare & initializeint x = 5;
Brace initializationint x{5};
Constantconst double PI = 3.14159;
Compile-time constantconstexpr int N = 10;
Reference (alias)int &r = x;
Pointerint *p = &x;
Dereference a pointer*p = 10;
Type inferenceauto y = 3.14;

Control flow

StatementSyntax
If / elseif (x > 0) { ... } else { ... }
Switchswitch (n) { case 1: ...; break; default: ...; }
While loopwhile (i < n) { ... }
Do-while loopdo { ... } while (i < n);
For loopfor (int i = 0; i < n; i++) { ... }
Range-based forfor (auto x : vec) { ... }
Range-based by referencefor (auto &x : vec) { ... }
Break / continuebreak; exits a loop, continue; skips to next iteration

Functions

OperationSyntax
Define a functionint add(int a, int b) { return a + b; }
No return valuevoid greet() { ... }
Default argumentsint pow(int b, int e = 2) { ... }
Pass by referencevoid inc(int &x) { x++; }
Const reference (no copy)void print(const std::string &s) { ... }
Overloadingint max(int a, int b); and double max(double a, double b);
Lambdaauto f = [](int x) { return x * 2; };
Lambda with captureauto g = [n](int x) { return x + n; };

Classes & OOP

OperationSyntax
Define a classclass Dog { ... };
Access specifierspublic:, private:, protected:
Member variablestd::string name;
ConstructorDog(std::string n) : name(n) {}
Destructor~Dog() { ... }
Member functionvoid bark() { ... }
Create an objectDog d("Rex");
Inheritanceclass Puppy : public Dog { ... };
Virtual functionvirtual void speak();

STL containers

Common containers from the standard library.

ContainerUse & example
std::vector<int>Dynamic array: v.push_back(1); v.size();
std::stringText: s += "!"; s.length();
std::array<int, 3>Fixed-size array with bounds info
std::map<K, V>Sorted key-value: m["a"] = 1;
std::unordered_map<K, V>Hash map (faster lookup, no order)
std::set<T>Sorted unique values: s.insert(5);
std::pair<A, B>Two values: make_pair(1, "x")
std::queue / std::stackFIFO queue / LIFO stack adapters

STL algorithms & iterators

From <algorithm>; most take a begin/end iterator range.

OperationSyntax
Begin / end iteratorsv.begin(), v.end()
Sortstd::sort(v.begin(), v.end());
Sort descendingstd::sort(v.begin(), v.end(), std::greater<int>());
Find a valueauto it = std::find(v.begin(), v.end(), 5);
Count matchesstd::count(v.begin(), v.end(), 5);
Min / max elementstd::max_element(v.begin(), v.end());
Sum a rangestd::accumulate(v.begin(), v.end(), 0);
Transform each elementstd::transform(v.begin(), v.end(), v.begin(), fn);

Smart pointers & modern C++

Prefer smart pointers over raw new/delete for automatic cleanup.

FeatureSyntax
Unique ownershipauto p = std::make_unique<Dog>("Rex");
Shared ownershipauto p = std::make_shared<Dog>("Rex");
Non-owning referencestd::weak_ptr<Dog> w = p;
Move semanticsauto v2 = std::move(v1);
Nullptrint *p = nullptr;
Structured bindingsauto [key, val] = *it;
Optional valuestd::optional<int> maybe;
Templatestemplate <typename T> T add(T a, T b) { return a + b; }

The C++ syntax, STL containers, and modern features you reach for most, on one page. This C++ cheat sheet is a quick reference for writing C++ - the data types, references, classes, the standard library containers and algorithms, and the smart pointers that replace raw new/delete.

Everything here is standard C++ (C++11 and later) and compiles with g++ or clang++. Copy what you need, or try any snippet live in the C++ playground - no compiler to install.

C++ cheat sheet FAQ

Is this C++ cheat sheet free?
Yes. This C++ cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up syntax, an STL container, or a smart pointer.
What is the difference between a pointer and a reference in C++?
A pointer is a variable that holds an address; it can be null, reassigned to point elsewhere, and you dereference it with *p. A reference (int &r = x) is an alias for an existing variable - it must be bound when declared, can never be null or rebound, and is used like the variable itself. Use references for cleaner pass-by-reference parameters and pointers when you need optional or reassignable indirection.
Should I use new/delete or smart pointers?
Prefer smart pointers. std::unique_ptr and std::shared_ptr (via make_unique/make_shared) free their memory automatically when they go out of scope, which prevents the leaks and double-frees that come with manual new/delete. Reach for raw new/delete only in low-level code that has a specific reason.
Can I practice C++ online?
Yes. Open the C++ playground to compile and run any snippet from this cheat sheet in your browser - no compiler to install. When you want structure, Coddy's free interactive C++ course takes you from variables and loops to classes and the STL step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common building blocks (types, control flow, functions) down to advanced ones (the STL and smart pointers), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn C++ with Coddy

GET STARTED