# C++ Cheat Sheet: C++20 and C++23 Syntax, STL and Ranges

Source: https://srvscripts.com/guides/cpp-cheat-sheet/
Updated: 2026-10-09
Publisher: srvScripts (https://srvscripts.com/)

**Short answer:** Compile with `g++ -std=c++23 -Wall -Wextra -O2 -o app main.cpp`. Prefer `std::vector`, `std::string` and `std::unordered_map` over raw arrays and `new`; own heap objects with `std::unique_ptr`. C++20 adds concepts, ranges, `std::format` and `<=>`; C++23 adds `std::print`, `std::expected` and `std::ranges::to`. GCC 16 compiles as `gnu++20` by default, so pass `-std=c++23` to get the newer library features.

The examples in this C++ cheat sheet were run with GCC 14.2 (g++ -std=c++23) and CMake 3.28 on Ubuntu 24.04 on 9 October 2026. Compiler defaults for GCC 16 were checked against the official documentation.

## Compile and build

| Command | What it does |
| --- | --- |
| g++ -std=c++20 -Wall -Wextra -O2 -o app main.cpp | C++20 build with common warnings |
| g++ -std=c++23 ... | C++23. std::print needs GCC 14+ (libstdc++) or a recent libc++ |
| clang++ -std=c++23 -stdlib=libc++ ... | Clang with the LLVM standard library |
| -g -fsanitize=address,undefined | Memory and undefined-behaviour checks in test builds |
| -Wconversion -Wshadow | Extra warnings worth enabling on new code |
| -pthread | Threads support on older toolchains |
| cmake -B build -DCMAKE_BUILD_TYPE=Release | Configure a CMake project into build/ |
| cmake --build build -j | Build it in parallel |

```
cmake_minimum_required(VERSION 3.20)
project(app LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(app main.cpp)
target_compile_options(app PRIVATE -Wall -Wextra)
```

## Variables, types and control flow

| Syntax | What it does | Example |
| --- | --- | --- |
| auto | Type deduced from the initialiser | auto n = 42; |
| const / constexpr | Read-only / usable at compile time | constexpr int sq(int x) { return x * x; } |
| consteval | Function that must run at compile time (C++20) | consteval int cube(int x) |
| int& r = n; | Reference: another name for n | void f(const std::string& s); |
| {} initialisation | Uniform init; blocks narrowing conversions | std::vector v{1, 2, 3}; |
| std::string_view | Non-owning view of a string; cheap to pass | void log(std::string_view msg); |
| enum class | Scoped, strongly typed enum | enum class Level { Low, High }; |
| nullptr | Null pointer; never use NULL or 0 | int* p = nullptr; |
| for (const auto& x : v) | Range-based for loop |  |
| if (auto it = m.find(k); it != m.end()) | if with an initialiser |  |
| static_cast(x) | Explicit, checked conversion | static_cast(Level::High) |
| 1'000'000 | Digit separators |  |

## Containers and common operations

| Container | Use it for | Key operations |
| --- | --- | --- |
| std::vector | Default choice: contiguous, growable | push_back, emplace_back, at(i), size(), reserve(n) |
| std::array | Fixed size known at compile time | a[i], a.size() |
| std::string | Owning text | +=, substr, find, starts_with (C++20) |
| std::map | Sorted keys | m[k] = v, insert_or_assign, contains(k) (C++20) |
| std::unordered_map | Fast lookup, no order | m[k]++, find, erase |
| std::set | Sorted unique values | insert, contains |
| std::deque | Fast push and pop at both ends | push_front, pop_back |

```
std::map ports{{"ssh", 22}, {"https", 443}};
ports["http"] = 80;
for (const auto& [name, port] : ports)      // structured bindings
    std::println("{}={}", name, port);

std::vector v{5, 3, 8, 1};
std::erase_if(v, [](int x) { return x % 2 == 0; });   // C++20
```

`m[k]` inserts a default value when the key is missing. Use `contains` or `find` when you only want to read.

## Ranges, algorithms and formatting

| Syntax | What it does |
| --- | --- |
| std::ranges::sort(v); | Sort a whole container, no begin/end pair |
| std::ranges::find(v, 42) | Iterator to the first match, or v.end() |
| std::ranges::count_if(v, pred) | Count matching elements |
| std::ranges::max(v) | Largest value |
| v | std::views::filter(pred) | Lazy filtered view |
| | std::views::transform(fn) | Lazy mapped view |
| std::views::iota(1, 11) | Numbers 1 to 10 |
| | std::ranges::to() | C++23: materialise a view into a container |
| std::format("{:>8}", s) | C++20 Python-style formatting into a std::string |
| std::print / std::println | C++23: format straight to stdout |

```
auto squares = std::views::iota(1, 11)
             | std::views::filter([](int x) { return x % 2 == 0; })
             | std::views::transform([](int x) { return x * x; })
             | std::ranges::to();          // 4 16 36 64 100

std::println("{:>8}|{:7} {}", n, ip);
}
```

| Syntax | What it does |
| --- | --- |
| std::filesystem::exists(p) | Check a path (namespace fs = std::filesystem;) |
| fs::directory_iterator(dir) | List a directory; recursive_directory_iterator walks it |
| std::jthread t{fn}; | C++20 thread that joins itself on destruction |
| std::scoped_lock lock{m}; | Lock one or more mutexes until the end of scope |
| std::atomic n{0}; n.fetch_add(1); | Lock-free counter |
| std::async(std::launch::async, fn) | Run a task and get a std::future |

Data races are undefined behaviour. Protect shared data with a mutex or an atomic, and build test binaries with `-fsanitize=thread` to find races.

**Official documentation (checked 9 October 2026):** [C++ Standards Support in GCC](https://gcc.gnu.org/projects/cxx-status.html) · [libstdc++ implementation status](https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html) · [GCC 16 Changes (C++20 by default)](https://gcc.gnu.org/gcc-16/changes.html) · [Clang C++ Language Status](https://clang.llvm.org/cxx_status.html) · [WG21 N4950 (C++23 working draft)](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf) · [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) · [CMake: CXX_STANDARD](https://cmake.org/cmake/help/latest/prop_tgt/CXX_STANDARD.html)

## C++ Cheat Sheet at a glance

In short: A compact C++20 and C++23 reference covering compiling, the STL, ranges, formatting, classes, concepts, error handling and threads.

C++ Cheat Sheet: what this guide covers.

**Related guides:** [C Cheat Sheet: C17 and C23 Syntax, Memory and gcc Flags](https://srvscripts.com/guides/c-cheat-sheet/) · [Rust Cheat Sheet: Cargo, Ownership, Enums and Errors](https://srvscripts.com/guides/rust-cheat-sheet/) · [C# Cheat Sheet: Syntax, LINQ and .NET 10 Essentials](https://srvscripts.com/guides/csharp-cheat-sheet/).
