Quick reference guide for C++. Essential syntax, memory management, STL containers, and common patterns for systems programming.
Hello World
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl; // Standard output
return 0;
}
Variables
int x = 42; // integer
double pi = 3.14; // floating point
std::string name = "Alice"; // string class
bool flag = true; // boolean
char c = 'A'; // character
// Type modifiers
unsigned int u = 100; // Unsigned
long long big = 1000000; // Long integer
float f = 3.14f; // Single precision
// Auto type deduction (C++11)
auto y = 42; // Compiler infers int
auto text = "Hello"; // Compiler infers const char*
Control Flow
If/Else
if (x > 10) {
std::cout << "x is big\n";
} else {
std::cout << "x is small\n";
}
if (x > 10) {
std::cout << "big\n";
} else if (x > 5) {
std::cout << "medium\n";
} else {
std::cout << "small\n";
}
// Ternary operator
int result = (x > 10) ? 100 : 0;
Switch
switch (x) {
case 10:
std::cout << "ten\n";
break;
case 20:
std::cout << "twenty\n";
break;
default:
std::cout << "other\n";
}
For Loops
// Traditional for loop
for (int i = 0; i < 5; i++) {
std::cout << i << "\n";
}
// Range-based for loop (C++11)
int nums[] = {1, 2, 3};
for (int n : nums) {
std::cout << n << "\n";
}
std::vector<int> vec = {4, 5, 6};
for (int n : vec) {
std::cout << n << "\n";
}
// With auto
for (auto n : vec) {
std::cout << n << "\n";
}
While Loops
while (x > 0) {
x--;
std::cout << x << "\n";
}
// Do...while
do {
x--;
} while (x > 0);
Functions
int add(int a, int b) {
return a + b;
}
std::cout << add(2, 3) << "\n";
// Function overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// Default parameters
void greet(std::string name = "World") {
std::cout << "Hello, " << name << "\n";
}
// Pass by reference
void increment(int& x) {
x++;
}
// Pass by pointer
void setValue(int* ptr, int value) {
*ptr = value;
}
Arrays / Vectors
Arrays
int nums[] = {1, 2, 3}; // Fixed-size array
int arr[5] = {1, 2, 3, 4, 5}; // Explicit size
for (int n : nums) {
std::cout << n << "\n";
}
// Array size
int size = sizeof(nums) / sizeof(nums[0]);
Vectors
#include <vector>
std::vector<int> vec = {4, 5, 6}; // Dynamic array
vec.push_back(7); // Add to end
vec.pop_back(); // Remove from end
vec.size(); // Size
vec[0]; // Access by index
vec.at(0); // Safe access (throws if out of bounds)
// Iterate
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << "\n";
}
// Range-based for
for (int n : vec) {
std::cout << n << "\n";
}
Other STL Containers
#include <string>
#include <map>
#include <set>
#include <unordered_map>
// String
std::string str = "Hello";
str.length();
str += " World";
str.substr(0, 5);
// Map
std::map<std::string, int> person;
person["age"] = 30;
person["name"]; // Access (creates if doesn't exist)
// Set
std::set<int> numbers = {1, 2, 3};
numbers.insert(4);
numbers.find(2); // Returns iterator
// Unordered map (hash map)
std::unordered_map<std::string, int> hash_map;
hash_map["key"] = 42;
Input
std::string input_name;
std::cout << "Enter your name: ";
std::cin >> input_name; // Whitespace-delimited
std::cout << "Hello " << input_name << "\n";
// Full line input
std::string full_line;
std::cout << "Enter a line: ";
std::getline(std::cin, full_line); // Reads entire line
std::cout << "You entered: " << full_line << "\n";
// Number input
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << "\n";
Pointers & References
int x = 42;
int* ptr = &x; // Pointer to x
int& ref = x; // Reference to x
*ptr = 100; // Dereference pointer
ref = 200; // Modify through reference
// Null pointer
int* null_ptr = nullptr; // C++11 (prefer over NULL)
// Dynamic allocation (avoid if possible)
int* dynamic = new int(42);
delete dynamic; // Must delete what you new
// Smart pointers (preferred)
#include <memory>
std::unique_ptr<int> smart = std::make_unique<int>(42);
// Automatically deleted when out of scope
Classes
class Person {
private:
std::string name;
int age;
public:
// Constructor
Person(std::string n, int a) : name(n), age(a) {}
// Getter
std::string getName() const {
return name;
}
// Setter
void setAge(int a) {
age = a;
}
// Method
void greet() const {
std::cout << "Hello, I'm " << name << "\n";
}
};
Person person("Alice", 30);
person.greet();
File Operations
#include <fstream>
// Reading
std::ifstream file("file.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << "\n";
}
file.close();
// Writing
std::ofstream out("file.txt");
out << "Hello, World!\n";
out.close();
// Check if file opened
if (file.is_open()) {
// File operations
} else {
std::cerr << "Failed to open file\n";
}
Error Handling
#include <stdexcept>
// Throwing exceptions
void divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
return a / b;
}
// Catching exceptions
try {
int result = divide(10, 0);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
}
Tips
- Always prefer stack allocation (
int x;) overnew/deleteunless necessary.
- If you must allocate dynamically, use smart pointers (
std::unique_ptr,std::shared_ptr) to avoid leaks.
- Remember to
#includenecessary headers (<iostream>,<vector>,<string>).
- Use RAII (Resource Acquisition Is Initialization) to manage resources safely.
std::cininput is whitespace-delimited; usestd::getline()for full lines.
- Watch for buffer overflows with arrays; prefer
std::vectororstd::string.
- C++ variables are strongly typed; type conversions are explicit.
- Use
constfor values that shouldn't change;constcorrectness is important.
- Prefer range-based for loops (
for (auto x : container)) when possible.
- Use
autofor type deduction when the type is obvious from context.
- Initialize variables; uninitialized variables contain garbage values.
- Use references (
&) instead of pointers when you don't need null or reassignment.
- Prefer standard library containers (
std::vector,std::string) over C-style arrays.
- Use
nullptrinstead ofNULLor0for null pointers (C++11).