Daily C++ Tip 7

A sorted map backed by vectors (std::flat_map, C++23)

A flat_map keeps keys sorted in vectors instead of a node tree.

std::flat_map keeps keys sorted like a map but stores them in vectors, so iteration is cache-friendly and there is no per-node allocation.

#include <flat_map>
#include <iostream>
#include <string>

int main() {
    // Sorted associative container backed by vectors, not a node tree.
    std::flat_map<std::string, int> scores;
    scores["ada"] = 95;
    scores["grace"] = 88;
    scores["ada"] += 5;
    for (auto [name, score] : scores) {
        std::cout << name << ": " << score << '\n';
    }
    std::cout << "size=" << scores.size() << '\n';
}

Observed output:

ada: 100
grace: 88
size=2

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.