C++ Cheatsheet

kuniga.me > Docs > C++ Cheatsheet

C++ Cheatsheet

Syntax for common tasks I run into often. Assumes C++17.

Index

  1. Basic Types
    1. Conversions
      1. int to string
  2. Collections
    1. Hash Map
      1. Import
      2. Initialization
      3. Access
      4. Insert
      5. Iterating
      6. Search
    2. Vector
      1. Initialization
      2. Iterate
  3. Object-Oriented
    1. Class
      1. Constructor
      2. Instantiate
  4. Files
    1. Check if file exists
    2. Create directory
    3. Read from file
    4. Write to file
  5. Functional
    1. Lambda

Basic Types

Conversions

int to string

#include <string>
std::string = to_string(10);

Collections

Hash Map

In C++ unordered_map implements a hash map. Search, insertion, and removal of elements have average constant-time complexity.

Import

#include <unordered_map>

Initialization

Empty map:

std::unordered_map<std::string, int> h;

Access

std::cout << h["key"] << std::endl;

Insert

h["key"] = 100;

Iterating

x is a pair (key, value).

for (auto x:h) {
    std::cout << x.first << ", " << x.second << std::endl;
}
bool has_key = h.find("key") != h.end();

Vector

Initialization

std::vector<int> vec = {10, 20, 30};

Iterate

for(auto e:vec) {
    std::cout << e << std::endl;
}

Object-Oriented

Class

Constructor

Defining constructor outside class definition:

class Point {
    private:
        int x;
        int y;
    public:
        Line();
};

Point::Point(void) {
    x = 0;
    y = 0;
}

Point::Point(int _x, int _y) {
    x = _x;
    y = _y;
}

Explicit initialization:

Point::Point(int x, int y): x(x), y(y)  {}

Instantiate

// Automatically destroyed when leaving scope
Point point(10, 20);

// Only destroyed when called w/ delete
Point point = new Point(10, 20);

Files

Check if file exists

Works for directories too.

#include <filesystem>
namespace fs = std::filesystem;

bool file_exists = fs::exists("path");

Create directory

#include <filesystem>
namespace fs = std::filesystem;

fs::create_directory("path");

Read from file

#include <fstream>

std::ifstream my_file("filename");
if (my_file.is_open()) {
    while (getline(my_file, line)) {
        std::cout << line << std::end;
    }
}

Write to file

#include <fstream>

std::ofstream my_file("filename");
if (my_file.is_open()) {
    my_file << "a line" << std::end;
}

Functional

Lambda

auto is_less_than = [](auto a, auto b) {
    return a < b;
};
is_less_than(3, 3.4); // true

With bindings:

int target = 5;
auto is_less_than_target = [target](auto a) {
    return a < target;
};
is_less_than_target(3); // true

With references bindings:

int target = 5;
auto dec = [&target]() {
    target--;
};
dec();
target; // 4