Language: EN

cheatsheet-cpp

C++ Cheatsheet

It is a general-purpose programming language, object-oriented, and an extension of C. It is widely used in the development of system software, applications, and video games.

Introduction to C++

Compiling a C++ program

Use a compiler like g++ or clang++ to compile .cpp files.

g++ program.cpp -o program

Basic structure of a program

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

Comments

To write single-line or multi-line comments.

// Single-line comment

/*
  Multi-line comment
*/

Namespaces

Namespaces organize code and prevent name collisions.

namespace MySpace {
    int value = 10;
}

cout << MySpace::value;

The most common is std.

using namespace std; // Prevents having to write std:: before every standard library function.

Modules

They allow dividing programs into more manageable and efficient modules.

export module math;
export int sum(int a, int b) { return a + b; }

Variables and Types

Primitive Types

Basic types include:

  • int: Integers
  • float: Floating-point numbers
  • double: Double precision numbers
  • char: Characters
  • bool: Booleans (true or false)

Type Modifiers

Modifiers expand primitive data types.

  • short: Small integer
  • long: Large integer
  • unsigned: Unsigned (only positive values)

Constant Expressions

Allow evaluating functions or variables at compile time.

constexpr int square(int x) { return x * x; }
constexpr int result = square(5);  // Evaluated at compile time

Automatic Type Declaration

Allows the compiler to deduce the type of the variable.

auto x = 10;  // x is of type int
auto y = 3.14; // y is of type double

Constinit

Ensures a global variable is initialized at compile time.

constinit int x = 42;

Operators

Arithmetic Operators

Addition (+), subtraction (-), multiplication (*), division (/), modulo (%).

Relational Operators

Equality (==), inequality (!=), greater (>), less (<), greater or equal (>=), less or equal (<=).

Logical Operators

Logical AND (&&), logical OR (||), negation (!).

Assignment Operators

Equals (=), addition assignment (+=), subtraction assignment (-=), etc.

Spaceship Operator (<=>)

Allows making complete comparisons.

#include <compare>

int a = 1, b = 2;
auto result = a <=> b;

Input and Output

Output with cout

Displays data on the console.

cout << "Value: " << variable << endl;

Input with cin

Captures data from the user.

int number;
cin >> number;

Control Flow

Conditionals

If - Else

Evaluates a condition and executes code depending on the result.

if (condition) {
    // code if true
} else {
    // code if false
}

Switch

Structure for handling multiple cases.

switch (value) {
    case 1:
        // code for case 1
        break;
    case 2:
        // code for case 2
        break;
    default:
        // code for other cases
}

Loops

For Loop

Used for controlled iterations.

for (int i = 0; i < 10; i++) {
    cout << i << endl;
}

While Loop

Repeats while a condition is true.

int i = 0;
while (i < 10) {
    cout << i << endl;
    i++;
}

Do-While Loop

Guarantees at least one execution of the code block.

int i = 0;
do {
    cout << i << endl;
    i++;
} while (i < 10);

Range-Based For Loops

Facilitate iteration over containers.

std::vector<int> vec = {1, 2, 3};
for (auto &v : vec) {
    std::cout << v << std::endl;
}

Functions

Function Declaration

A function takes parameters, performs a task, and optionally returns a value.

int add(int a, int b) {
    return a + b;
}

Function Prototype

Declare the function before main() and define it after main().

int add(int a, int b); // Prototype

int main() {
    cout << add(5, 3) << endl;
    return 0;
}

int add(int a, int b) {
    return a + b;
}

Function Overloading

Allows defining multiple functions with the same name but different parameters.

int sum(int a, int b) { return a + b; }
float sum(float a, float b) { return a + b; }

Functions with Default Values

int multiply(int a, int b = 2) {
    return a * b;
}

Lambda Functions

Allow defining inline anonymous functions, very useful for callbacks or to use in algorithms.

auto sum = [](int a, int b) { return a + b; };
std::cout << sum(5, 3);  // Prints 8

Collections

Arrays

Declaration and access to arrays

int arr[5] = {1, 2, 3, 4, 5};
cout << arr[0];  // Prints 1

STL Containers

Common STL (Standard Template Library) containers

  • Vector: Dynamic array.
  • Map: Key-value data structure.
  • Set: Set of unique elements.
#include <vector>
#include <map>
#include <set>

std::vector<int> vec = {1, 2, 3};
std::map<int, std::string> map = {{1, "One"}, {2, "Two"}};
std::set<int> set = {1, 2, 3};

List Initialization

Allows directly initializing containers or variables using braces {}.

std::vector<int> vec = {1, 2, 3, 4, 5};
int arr[] = {1, 2, 3};

Iterators

Facilitate navigation through containers.

std::vector<int> vec = {1, 2, 3};
for (auto it = vec.begin(); it != vec.end(); ++it) {
    std::cout << *it << std::endl;
}

Ranges

Allow more expressive operations on containers.

#include <ranges>

std::vector<int> nums = {1, 2, 3, 4, 5};
auto even_nums = nums | std::ranges::views::filter([](int n) { return n % 2 == 0; });

Pointers

Pointers

A pointer stores the address of a variable.

int x = 10;
int* p = &x; // p points to the address of x
cout << *p;  // Prints the value of x

Using nullptr

Used instead of NULL to represent a null pointer more safely.

int* p = nullptr;  // Better than using NULL

Smart Pointers

Smart pointers like std::unique_ptr and std::shared_ptr manage memory automatically, preventing memory leaks.

#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(10);  // C++14 and later
std::shared_ptr<int> sharedPtr = std::make_shared<int>(20);

Move Semantics

Optimizes performance by avoiding unnecessary copies.

class MyClass {
public:
    MyClass(const MyClass&) = delete; // Prevents copies
    MyClass(MyClass&&) = default;  // Allows moves
};

References

Concept of References

References are aliases for existing variables. They allow manipulating the original variable’s value without creating a copy.

int original = 30;
int &ref = original;  // ref is a reference to original
  • Changes to the reference affect the original variable.
  • References are useful for passing large data structures to functions without making copies.

Dynamic Memory Management

new and delete

Used to allocate and free memory on the heap.

int* p = new int;  // Allocate memory
*p = 10;
delete p;         // Free memory

Dynamic Arrays

int* arr = new int[5];  // Allocate an array
delete[] arr;          // Free the array

Classes and Object-Oriented Programming

Class Definition

A class is a blueprint for creating objects.

class Person {
  public:
    string name;
    int age;
    void greet() {
        cout << "Hello, I am " << name << endl;
    }
};

Object Creation

Person p;
p.name = "John";
p.age = 25;
p.greet();

Constructor

Initializes an object upon creation.

class Person {
  public:
    string name;
    Person(string n) {
        name = n;
    }
};

Destructor

Cleans up the object when it is no longer needed.

~Person() {
    cout << "Object destroyed" << endl;
}

Simple Inheritance

A class can inherit attributes and methods from another.

class Student : public Person {
  public:
    int enrollment;
};

Polymorphism with Classes

Allows using the same interface for different types of objects.

class Animal {
public:
    virtual void makeSound() const { std::cout << "Animal sound" << std::endl; }
};

class Dog : public Animal {
public:
    void makeSound() const override { std::cout << "Woof!" << std::endl; }
};

Exceptions

Try-Catch Blocks

Handle exceptions

try {
    throw std::runtime_error("Error");
} catch (const std::exception &e) {
    std::cout << "Caught exception: " << e.what() << std::endl;
}

Throwing Exceptions

You can throw exceptions in C++ using throw.

void divide(int a, int b) {
    if (b == 0) {
        throw std::invalid_argument("Division by zero");
    }
    std::cout << a / b << std::endl;
}

Standard Libraries

iostream

Provides functions for input and output.

#include <iostream>
using namespace std;

cout << "Hello" << endl;
cin >> variable;

vector

A dynamic data structure that can change size.

#include <vector>
vector<int> v = {1, 2, 3};
v.push_back(4);
cout << v[0];  // Prints 1

algorithm

Offers algorithm functions like searching and sorting.

#include <algorithm>
vector<int> v = {4, 1, 3, 2};
sort(v.begin(), v.end());  // Sorts the vector

Macros and Templates

Macros

Define preprocessed functions or constant values.

#define PI 3.14159
#define square(x) ((x) * (x))

Function Template

Allows defining generic functions that operate with any data type.

template <typename T>
T add(T a, T b) {
    return a + b;
}

Class Template

Defines generic classes.

template <class T>
class Box {
  public:
    T value;
    Box(T v) : value(v) {}
};

Concepts

Are constraints that allow defining clear interfaces for templates.

template <typename T>
concept Numeric = std::is_arithmetic_v<T>;

template <Numeric T>
T multiply(T a, T b) {
    return a * b;
}

Files

Reading and Writing Files

Use ifstream for reading and ofstream for writing.

#include <fstream>
ofstream file("output.txt");
file << "Hello File" << endl;
file.close();

ifstream input("input.txt");
string line;
while (getline(input, line)) {
    cout << line << endl;
}
input.close();

Concurrency

Threads

Managing threads with std::thread

#include <thread>

void function() {
    std::cout << "Thread running" << std::endl;
}

int main() {
    std::thread thread(function);  // Create a new thread
    thread.join();  // Wait for the thread to finish
}

Mutex and Conditions

Synchronization with mutex

#include <mutex>

std::mutex mtx;

void print(int i) {
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "Value: " << i << std::endl;
}

Coroutines

Allow suspending and resuming functions.

#include <coroutine>

std::future<void> example() {
    co_await std::chrono::seconds(1);
    std::cout << "Done!" << std::endl;
}

Error Handling and Debugging

assert for debugging

Checks conditions at runtime.

#include <cassert>
int x = 5;
assert(x == 5);  // Passes, nothing happens

cerr for errors

Displays error messages to the standard error output

cerr << "Error: Invalid variable" << endl;