C++ 23 cheatsheet
C++ 23: Containers and algorithms
11 common C++ 23 tasks.
Use a vector
A growable array. emplace_back constructs the element in place.
std::vector<int> v = {3, 1, 2};
v.push_back(4);
v.emplace_back(5);
std::cout << v.size() << ' ' << v.front() << '\n';
Use a hash map
Look up values by key. contains is available since C++20.
std::unordered_map<std::string, int> ages{{"Ada", 36}, {"Grace", 45}};
ages["Linus"] = 28;
if (ages.contains("Ada")) std::cout << ages.at("Ada") << '\n';
Sort with a custom order
Sort descending by passing a lambda comparator.
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
Find the first match
Search with a predicate. The result is an iterator, end() if nothing matches.
auto it = std::find_if(v.begin(), v.end(), [](int n) { return n > 10; });
if (it != v.end()) std::cout << *it << '\n';
Sum a range
Add up the elements, starting from 0.
#include <numeric>
int total = std::accumulate(v.begin(), v.end(), 0);
Remove matching elements
Erase every element that satisfies a condition (C++20).
std::erase_if(v, [](int n) { return n % 2 == 0; });
Sort with ranges
Pass the container directly instead of a begin and end pair (C++20).
std::ranges::sort(v);
Chain lazy views
Filter and transform without creating intermediate containers (C++20).
auto squares = v | std::views::filter([](int n) { return n % 2 == 1; })
| std::views::transform([](int n) { return n * n; });
for (int n : squares) std::cout << n << ' ';
Represent a missing value
std::optional holds a value or nothing, instead of a sentinel like -1.
std::optional<int> find_id(std::string_view name);
if (auto id = find_id("Ada")) std::cout << *id << '\n';
Hold one of several types
A type-safe union, visited with std::visit.
std::variant<int, std::string> value = "hello";
std::visit([](const auto& x) { std::cout << x << '\n'; }, value);
View a contiguous range
A non-owning view over an array or vector (C++20).
void print_all(std::span<const int> values) {
for (int n : values) std::cout << n << ' ';
}