Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 10 – Standard containers

std::flat_map and std::flat_set (C++23)

Use C++23 std::flat_map and std::flat_set for sorted data that is mostly read, build them in bulk with std::sorted_unique, and know what an insertion costs.

  • Intermediate
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Use flat containers for read-heavy sorted data
  • Write loops over a flat_map whose bindings compile and change its values
  • Explain their insertion cost
  • Build flat containers efficiently from bulk data
  • Choose which value a repeated key keeps when loading in bulk

Before you start

What you’ll learn · Before you start

What you will learn

  • Use flat containers for read-heavy sorted data
  • Write loops over a flat_map whose bindings compile and change its values
  • Explain their insertion cost
  • Build flat containers efficiently from bulk data
  • Choose which value a repeated key keeps when loading in bulk

Before you start

On this page

Loading 20,000 keys into a std::flat_map one emplace at a time shifted 100,388,524 keys, and as many values, to make room. std::flat_map and std::flat_set, new in C++23, are sorted containers with the interface of std::map and std::set, but without nodes. A flat_map keeps its keys in one sorted std::vector and its values in another, at the same positions, and a flat_set keeps one sorted vector. Lookups are binary search: A search of a sorted sequence that compares the target with the middle element and keeps only the half that can hold it, so n elements need at most about log2 n + 1 probes: 20 for a million. std::lower_bound and the flat containers' lookups work this way. over contiguous memory, so they are fast, a pass over every element is as fast as over a vector, and memory per element is little more than the elements themselves.

The cost is insertion: a new key in the middle shifts every later key and value, so a single insertion or erasure takes linear time. Use them for sorted data that is built once, or rarely changed, and then read many times.

Flat containers keep keys and values in sorted vectors

flat_basics.cpp C++ · flat_basics.cpp
// std::flat_map (C++23) has the interface of std::map, but keeps its keys in one sorted std::vector and its values
// in another, at the same positions. std::flat_set keeps one sorted vector of keys.
#include <flat_map>
#include <flat_set>
#include <print>
#include <string>

int main() {
    std::flat_map<std::string, int> stock{{"pens", 40}, {"ink", 7}, {"paper", 500}};
    stock["clips"] = 120;  // like std::map: operator[] inserts a missing key
    stock.erase("ink");
    std::println("{}", stock);
    std::println("keys {} and values {}", stock.keys(), stock.values());  // the two vectors themselves

    auto it = stock.find("paper");
    std::println("paper: {}, at position {}", it->second, it - stock.begin());  // random access iterators
    std::println("the second key: {}", stock.begin()[1].first);

    for (auto [item, count] : stock) count += 10;  // each element is a pair of references into the two vectors
    std::println("after adding 10 to every count: {}", stock);

    std::flat_set<int> marks{72, 91, 64, 91};
    std::println("{}, first mark at least 70: {}", marks, *marks.lower_bound(70));
#ifdef __cpp_lib_flat_map
    std::println("__cpp_lib_flat_map is defined: this library has std::flat_map");
#endif
}
Both libraries, then a loop that does not compile Python · flat_basics_session.py
from session import run

# flat_basics.cpp with both compilers and their standard libraries; then flat_proxy.cpp, which does not compile:
# grep keeps each compiler's first error, without the file and line in front.
run("""
clang++ -std=c++23 -Wall -Wextra flat_basics.cpp -o flat_basics && ./flat_basics
g++-16 -std=c++23 -Wall -Wextra flat_basics.cpp -o flat_basics-gcc && ./flat_basics-gcc
clang++ -std=c++23 -Wall -Wextra flat_proxy.cpp -o flat_proxy 2>&1 | grep -m1 -o "error: .*"
g++-16 -std=c++23 -Wall -Wextra flat_proxy.cpp -o flat_proxy-gcc 2>&1 | grep -m1 -o "error: .*"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra flat_basics.cpp -o flat_basics && ./flat_basics
{"clips": 120, "paper": 500, "pens": 40}
keys ["clips", "paper", "pens"] and values [120, 500, 40]
paper: 500, at position 1
the second key: paper
after adding 10 to every count: {"clips": 130, "paper": 510, "pens": 50}
{64, 72, 91}, first mark at least 70: 72
__cpp_lib_flat_map is defined: this library has std::flat_map
$ g++-16 -std=c++23 -Wall -Wextra flat_basics.cpp -o flat_basics-gcc && ./flat_basics-gcc
{"clips": 120, "paper": 500, "pens": 40}
keys ["clips", "paper", "pens"] and values [120, 500, 40]
paper: 500, at position 1
the second key: paper
after adding 10 to every count: {"clips": 130, "paper": 510, "pens": 50}
{64, 72, 91}, first mark at least 70: 72
__cpp_lib_flat_map is defined: this library has std::flat_map
$ clang++ -std=c++23 -Wall -Wextra flat_proxy.cpp -o flat_proxy 2>&1 | grep -m1 -o "error: .*"
error: non-const lvalue reference to type '_If<...>' cannot bind to a temporary of type '_If<...>'
$ g++-16 -std=c++23 -Wall -Wextra flat_proxy.cpp -o flat_proxy-gcc 2>&1 | grep -m1 -o "error: .*"
error: cannot bind non-const lvalue reference of type 'std::pair<const std::__cxx11::basic_string<char>&, int&>&' to an rvalue of type 'std::_Flat_map_impl<std::__cxx11::basic_string<char>, int, std::less<std::__cxx11::basic_string<char> >, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char> > >, std::vector<int, std::allocator<int> >, false>::_Iterator<false>::reference' {aka 'std::pair<const std::__cxx11::basic_string<char>&, int&>'}

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 flat_basics_session.py

Apple clang 21’s libc++ and GCC 16’s libstdc++ both ship <flat_map> and <flat_set>, and both define the feature-test macro __cpp_lib_flat_map, which code can check, after including <version>, before it relies on the header. The interface is the one you know from std::map and std::set: operator[], erase, find, lower_bound and printing with std::println worked unchanged. What is new shows in the output:

  • keys() and values() return the two vectors themselves, read-only: ["clips", "paper", "pens"] and [120, 500, 40]. Code that needs only the keys, or only the values, can use them directly.
  • The iterators are random access, as a vector’s are: it - stock.begin() gave the position of "paper", and stock.begin()[1] read the second element without walking.
  • There is no node and no pair object inside the map. Dereferencing an iterator builds a temporary std::pair<const std::string&, int&>, a pair of references into the two vectors.

The diagram shows the stock map’s two vectors before and after one more insertion. A key and its value always share a position:

A flat_map as two vectors: keys clips, paper, pens over values 120, 500, 40; inserting ink moves paper and pens up.beforeafter emplace("ink", 7)keys, sortedvalueskeys, sortedvaluesclipspaperpens12050040clipsinknewpapermovedpensmoved1207new500moved40moveda binary search finds position 1;every later key and value moves up

A flat_map is two vectors, and an insertion shifts both

Text description of the diagram

The diagram shows a std::flat_map from names to counts, before and after one insertion.

  1. Before: the keys vector holds clips, paper and pens, in sorted order. The values vector holds 120, 500 and 40, each at the same position as its key.
  2. emplace("ink", 7) finds the place for ink with a binary search: position 1, between clips and paper.
  3. After: the keys vector holds clips, ink, paper and pens, and the values vector holds 120, 7, 500 and 40. To make room, paper and pens moved up one place, and so did their values, 500 and 40.

Every insertion and erasure moves all the keys and values after its position, so it takes time linear in the size of the map.

These flat container: std::flat_map, std::flat_set or one of their multi versions (C++23): an adaptor that keeps its keys sorted in a sequence container, std::vector by default, and a flat_map's values in a second one, so lookups are binary searches and insertions shift elements. are adaptors: what they cost is what their two vectors cost, which the next sections measure.

Checkpoint

Check: Two sorted vectors

  1. Question 1 of 2 How does a std::flat_map<K, V> store its elements by default?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: In two std::vectors, the keys sorted and each value at the same position as its key

    The keys and the values live in two separate sequence containers, std::vector unless you choose others. keys() and values() return them, and a binary search over the keys finds the position of the value.

  2. Question 2 of 2 it = stock.find("paper") in a std::flat_map of three items. What does it - stock.begin() give, and why does it compile at all?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 1, the position of paper, because flat_map iterators are random access, like a vector's

    The elements of a flat_map are positions in two vectors, so its iterators are random access: subtracting two of them gives a distance, and indexing an iterator reads an element without walking.

Its elements are pairs of references, so auto& does not compile

The last point of that list explains the two error messages. for (auto& [item, count] : stock) asks for a non-const reference to the temporary pair, which C++ does not allow, and both compilers refuse: Clang with “non-const lvalue reference … cannot bind to a temporary”, GCC naming the pair of references. Write for (auto [item, count] : stock), which copies the pair of references, so count still refers into the map and count += 10 changed the values; or const auto& to read, or auto&&. Code that switches from std::map to std::flat_map hits this error first.

Such a pair of references, built on the spot to stand for an element, is a proxy object: An object returned in place of a reference, standing for an element that cannot be referred to directly, as std::vector<bool>::reference stands for one bit. It points into its container and is valid only while the container lives. More in “C++ auto, decltype and type aliases”. Step through one dereference, then the loop that does not compile and the one that does:

Interactive · step by step What a flat_map iterator gives you Step through one dereference of an iterator, then the loop that does not compile and the one that does.
What a flat_map iterator gives you, step 5 of 5. Showing keys(): a vector, values(): a vector (130, 510, 50), an iterator, *it, a temporary pair, auto& [item, count], auto [item, count]. In focus: auto [item, count].*it buildsrefers to paperrefers to 500keys(): a vectorclips, paper, pensvalues(): a vector130, 510, 50an iteratorat position 1*it, a temporary pairtwo references: paper, 500auto& [item, count]error: cannot bindauto [item, count]copies the two references

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Two vectors, no pairs. The stock map keeps its keys in one vector and its values in another, at the same positions. Nowhere in the map is there a std::pair object.
  2. Dereferencing builds a pair. *it cannot return a reference to a pair that does not exist. It builds a temporary std::pair of a const reference to the key and a reference to the value: for position 1, paper and 500.
  3. auto& cannot bind. for (auto& [item, count] : stock) asks for a non-const reference to that temporary, which C++ does not allow. Both compilers refused it; Clang said that a non-const lvalue reference cannot bind to a temporary.
  4. auto copies the references. for (auto [item, count] : stock) copies the pair, and a copy of a reference still refers to the same value. count += 10 changed the map: clips 130, paper 510, pens 50, as the program printed.
  5. Two more ways that work. const auto& binds to the temporary to read, and auto&& binds to it too and can change the values through it. Only a non-const auto& is refused.

Every value in the figure is one the session printed: paper at position 1, and the counts 130, 510 and 50 after the loop that copies the pairs.

Checkpoint

Check: Pairs of references

  1. Question 1 of 2 Why does for (auto& [key, value] : fm) not compile for a std::flat_map fm?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Dereferencing an iterator returns a temporary pair of references, and auto& cannot bind to a temporary

    No pair object exists to refer to, because keys and values are in separate vectors. auto [key, value] copies the pair of references, so value still refers into the map, and const auto& or auto&& work too.

  2. Question 2 of 2 for (auto [item, count] : stock) count += 10; runs on a std::flat_map<std::string, int>. What happens to the map?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Every count goes up by 10, because the copied pair still holds references into the values vector

    The elements are std::pair<const std::string&, int&> objects built on the spot. auto copies such a pair, and the copy still refers to the same value, so count += 10 changes the map.

One insertion moves every key after its place

Every insertion into the middle shifts the later keys and values, and so does every erasure. That makes loading data one element at a time quadratic in the worst case. This program loads eight keys one emplace at a time and counts, before each one, the keys after the new key’s place:

one_by_one.cpp C++ · one_by_one.cpp
// Loading eight keys into a std::flat_map one emplace at a time. Before each emplace, the program counts the keys
// after the new key's place: those keys, and their values, move up one place to make room. The keys arrive in the
// order of the lesson's figure.
#include <flat_map>
#include <print>

int main() {
    const int arriving[] = {610, 140, 980, 370, 820, 50, 470, 260};
    std::flat_map<int, int> fm;
    long total = 0;
    int position = 0;
    for (int key : arriving) {
        long moved = fm.end() - fm.lower_bound(key);  // the keys after the new key's place
        fm.emplace(key, position++);
        total += moved;
        std::println("emplace({}): {} key{} moved up", key, moved, moved == 1 ? "" : "s");
    }
    std::println("keys {}", fm.keys());
    std::println("{} keys and as many values moved in all", total);
}
Keys moved by each emplace, with both libraries Python · one_by_one_session.py
from session import run

# one_by_one.cpp built and run with Apple clang and libc++, then with GCC 16 and libstdc++. The counts follow from the
# keys alone, so both libraries print the same.
run("""
clang++ -std=c++23 -Wall -Wextra one_by_one.cpp -o one_by_one && ./one_by_one
g++-16 -std=c++23 -Wall -Wextra one_by_one.cpp -o one_by_one-gcc && ./one_by_one-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra one_by_one.cpp -o one_by_one && ./one_by_one
emplace(610): 0 keys moved up
emplace(140): 1 key moved up
emplace(980): 0 keys moved up
emplace(370): 2 keys moved up
emplace(820): 1 key moved up
emplace(50): 5 keys moved up
emplace(470): 3 keys moved up
emplace(260): 5 keys moved up
keys [50, 140, 260, 370, 470, 610, 820, 980]
17 keys and as many values moved in all
$ g++-16 -std=c++23 -Wall -Wextra one_by_one.cpp -o one_by_one-gcc && ./one_by_one-gcc
emplace(610): 0 keys moved up
emplace(140): 1 key moved up
emplace(980): 0 keys moved up
emplace(370): 2 keys moved up
emplace(820): 1 key moved up
emplace(50): 5 keys moved up
emplace(470): 3 keys moved up
emplace(260): 5 keys moved up
keys [50, 140, 260, 370, 470, 610, 820, 980]
17 keys and as many values moved in all

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 one_by_one_session.py

The eight emplaces moved 17 keys in all, and as many values. Step through the same eight keys arriving in the same order; each round shifts the larger keys one place right, as an emplace does:

Interactive · step through it Eight keys arriving one at a time: each shifts the larger keys Each round takes the next value and shifts the larger values of the sorted part right to make room for it.
Array of 8: 610 140 980 370 820 50 470 260.6100140198023703820450547062607
  • being compared or looked at
  • being moved or written
  • in its final place
  • the key, pivot or target

Pseudo-code

  1. for i from 1 to n − 1:
  2. key ← a[i]; j ← i − 1
  3. while j ≥ 0 and a[j] > key:
  4. a[j + 1] ← a[j]; j ← j − 1
  5. a[j + 1] ← key

Start: 8 values. The left part is kept sorted; each round takes the next value and shifts the larger ones right to make room for it.

When it finishes: Sorted: 50 140 260 370 470 610 820 980.

Comparisons 0
Shifts 0

The figure’s shift count ends at 17, the program’s total. It finds each place by comparing from the right, where a flat_map runs a binary search, so the shifts are the same and the comparisons are not. In random order each new key lands, on average, in the middle of the keys already stored, so n insertions shift about n²/4 keys in all.

Key idea

Finding the place for a key is a quick binary search; making room is not: every key and value after the place moves, so one insertion or erasure is O(n), and loading one key at a time is quadratic.

Checkpoint

Check: What one insertion costs

  1. Question 1 of 2 What does inserting one new key into a std::flat_map of n elements cost?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: O(n), because every later key and value moves up one place

    Finding the place is a binary search, O(log n), but making room shifts the rest of both vectors. Inserting 20,000 keys in random order one at a time shifted about 100 million keys and as many values.

  2. Question 2 of 2 The eight keys 610, 140, 980, 370, 820, 50, 470 and 260 were emplaced into an empty std::flat_map in that order. How many keys moved in all?

    Type a number.

    A hint

    For each new key, count the keys already stored that are larger than it.

    Show the answer: Question 2 of 2

    Answer: 17 keys

    0 + 1 + 0 + 2 + 1 + 5 + 3 + 5 = 17, which is what one_by_one.cpp printed with both libraries, and as many values moved with them. The figure's shift count is the same 17.

Bulk loads sort once, and sorted input skips even that

This program loads 20,000 pairs that arrive in random order in four ways:

build.cpp C++ · build.cpp
// Loading 20,000 key-value pairs. Inserting into a flat_map one pair at a time shifts every later key and value up
// by one place; the range constructor appends everything, sorts once and removes duplicates; and when the data
// already arrives sorted, std::sorted_unique takes two vectors as they are, without sorting or checking anything.
// Times are the fastest of 7 runs; the count of shifted elements is computed, not timed.
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <flat_map>
#include <map>
#include <print>
#include <random>
#include <utility>
#include <vector>

using Clock = std::chrono::steady_clock;

long long check = 0;  // every load adds to it, so the optimiser cannot drop the work

template <class F>
double fastest_ms(F load) {
    double best = 1e300;
    for (int run = 0; run < 7; ++run) {
        auto start = Clock::now();
        check += load();
        std::chrono::duration<double, std::milli> took = Clock::now() - start;
        best = std::min(best, took.count());
    }
    return best;
}

int main() {
    const int n = 20'000;
    std::vector<std::pair<int, int>> rows;
    for (int i = 0; i < n; ++i) rows.emplace_back(i * 3, i);  // distinct keys
    std::mt19937 random(7);
    for (int i = n - 1; i > 0; --i) std::swap(rows[i], rows[random() % (i + 1)]);  // a shuffle every library repeats

    long long shifted = 0;
    double one = fastest_ms([&] {
        std::flat_map<int, int> fm;
        shifted = 0;
        for (auto [key, value] : rows) {
            shifted += fm.end() - fm.lower_bound(key);  // the elements that move up to make room
            fm.emplace(key, value);
        }
        return fm.size() + fm.begin()->second;
    });
    double range = fastest_ms([&] {
        std::flat_map<int, int> fm(rows.begin(), rows.end());
        return fm.size() + fm.begin()->second;
    });
    // Data that arrives sorted, for example from a file written in key order: two vectors, ready before the clock starts.
    auto sorted = rows;
    std::ranges::sort(sorted);
    std::vector<int> sorted_keys, sorted_values;
    for (auto [key, value] : sorted) {
        sorted_keys.push_back(key);
        sorted_values.push_back(value);
    }
    double presorted = fastest_ms([&] {
        auto keys = sorted_keys;  // copies, so that every run starts from the same input
        auto values = sorted_values;
        std::flat_map<int, int> fm(std::sorted_unique, std::move(keys), std::move(values));
        return fm.size() + fm.begin()->second;
    });
    double tree = fastest_ms([&] {
        std::map<int, int> m;
        for (auto [key, value] : rows) m.emplace(key, value);
        return m.size() + m.begin()->second;
    });

    std::println("{} pairs in random order:", n);
    std::println("  flat_map, one emplace at a time:  {:8.3f} ms, {} keys and as many values shifted", one, shifted);
    std::println("  flat_map, range constructor:      {:8.3f} ms", range);
    std::println("  std::map, one emplace at a time:  {:8.3f} ms", tree);
    std::println("the same pairs, already sorted:");
    std::println("  flat_map with std::sorted_unique: {:8.3f} ms, copying the two vectors included", presorted);
    std::println("check: {}", check);
}
Four ways to load 20,000 pairs Python · build_session.py
from session import run

# build.cpp with -O2, with each compiler and its standard library.
run("""
clang++ -std=c++23 -O2 -Wall -Wextra build.cpp -o build
./build
g++-16 -std=c++23 -O2 -Wall -Wextra build.cpp -o build-gcc
./build-gcc
""")

Output

$ clang++ -std=c++23 -O2 -Wall -Wextra build.cpp -o build
$ ./build
20000 pairs in random order:
  flat_map, one emplace at a time:    20.806 ms, 100388524 keys and as many values shifted
  flat_map, range constructor:         1.095 ms
  std::map, one emplace at a time:     3.203 ms
the same pairs, already sorted:
  flat_map with std::sorted_unique:    0.004 ms, copying the two vectors included
check: 560000
$ g++-16 -std=c++23 -O2 -Wall -Wextra build.cpp -o build-gcc
$ ./build-gcc
20000 pairs in random order:
  flat_map, one emplace at a time:    22.443 ms, 100388524 keys and as many values shifted
  flat_map, range constructor:         1.245 ms
  std::map, one emplace at a time:     3.394 ms
the same pairs, already sorted:
  flat_map with std::sorted_unique:    0.004 ms, copying the two vectors included
check: 560000

This output changes from run to run: the times depend on the computer and on what else it is doing

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 build_session.py

  • One emplace at a time shifted 100,388,524 keys, and as many values, with both libraries: about n²/4 for n insertions in random order, because each new key lands, on average, in the middle of the keys already stored. It was the slowest way to build either container.
  • The range constructor took a small fraction of that time. Like insert(first, last) and insert_range, it appends all the pairs, sorts them once and removes duplicates, and the standard puts the cost of those insertions at N + M log M for M new elements added to a map of N. Prefer them whenever you have the data at hand.
  • std::map, one at a time, sat between the two: every insertion is O(log n), but each allocates a node.
  • std::sorted_unique: A tag passed to a flat container's constructor, insert or replace that promises the keys are already sorted and contain no duplicates, so the container takes them as they are. Nothing checks it outside the debug modes, and a false promise is undefined behaviour. tells the map that the input is already sorted and free of duplicates. The map then takes the two vectors as they are, without sorting or even checking them, which is why loading 20,000 pairs that arrived sorted took a few microseconds: the time of copying two vectors.

Follow the range constructor through the 20,000 pairs, then the shortcut for input that arrives sorted:

Interactive · stage by stage Loading a flat_map in bulk Step through the range constructor with 20,000 pairs in random order. The branch is input that already arrives sorted, without repeated keys.
Loading a flat_map in bulk, step 5 of 5. Showing 20,000 pairs arrive, Append them all, Sort once by key, Keep one per key, A sorted flat_map. In focus: presorted, A sorted flat_map.sorted_unique: as it is20,000 pairs arrivein random orderAppend them allno shifting yetSort once by keyN + M log M in allKeep one per keynot always the first valueA sorted flat_mapready to be read

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The input. The pairs arrive in random order. Inserted one emplace at a time, each would shift the keys after its place: 100,388,524 keys and as many values for 20,000 pairs, about n²/4.
  2. Append first. The range constructor, insert(first, last) and insert_range append every new pair at the end of the two vectors first, without shifting anything.
  3. One sort. Then they sort the new elements once and merge them with those already stored: the standard puts the cost at N + M log M for M new elements added to a map of N.
  4. Repeated keys. A key that appears more than once is kept once. Which of its values survives is not specified, because the sort need not keep equal keys in their input order: for 2,000 pairs with 100 keys, another value than the first won for 95 keys with libc++ and 93 with libstdc++.
  5. Sorted input. Pairs that already arrive sorted, with no key twice, can skip all of it: std::sorted_unique tells the map to take two vectors as they are, which took a few microseconds for 20,000 pairs, the time of copying the vectors.

The same rules hold for flat_set, with one container instead of two. To change many elements at once, take the containers out with std::move(fm).extract(), change them, and put them back with replace(keys, values), whose preconditions are the same as sorted_unique’s.

Checkpoint

Check: Loading in bulk

  1. Question 1 of 2 A file delivers 1,000,000 rows already sorted by key, without duplicates. What is the fastest correct way to build a std::flat_map from it?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Read the keys and values into two vectors and move them into the map with std::sorted_unique

    With std::sorted_unique the map takes the two vectors as they are: no sort, no shifting, not even a check in an ordinary build. The range constructor would work, but it sorts again, and emplacing one row at a time searches for the place of every row.

  2. Question 2 of 2 What does the range constructor of a std::flat_map do with pairs that arrive in random order?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It appends them all, sorts once and removes repeated keys

    The range constructor, insert(first, last) and insert_range append everything, sort once and remove duplicates, at a cost the standard puts at N + M log M for M new elements added to a map of N.

Mostly-read data: less memory, quicker lookups, much faster passes

The flat containers were designed for data that is read far more often than it changes. This program stores 50,000 names with an address each, as a symbol table, in a std::map and in a std::flat_map, and counts the bytes each one requests before timing lookups and a full pass:

read_heavy.cpp C++ · read_heavy.cpp
// A symbol table that is built once and then only read: 50,000 names, each with an address, in a std::map and in a
// std::flat_map. The program counts the bytes each one asked the allocator for, then times lookups of names that are
// present and a full pass over all values. Each round times both containers, one after the other, and the output
// shows the fastest of 15 rounds.
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <flat_map>
#include <format>
#include <functional>
#include <map>
#include <new>
#include <print>
#include <random>
#include <string>
#include <utility>
#include <vector>

inline std::size_t bytes = 0;  // bytes allocated and not yet freed, through Counting

template <class T>
struct Counting {
    using value_type = T;
    Counting() = default;
    template <class U>
    Counting(const Counting<U>&) noexcept {}
    T* allocate(std::size_t n) {
        bytes += n * sizeof(T);
        if (void* p = std::malloc(n * sizeof(T))) return static_cast<T*>(p);
        throw std::bad_alloc{};
    }
    void deallocate(T* p, std::size_t n) noexcept {
        bytes -= n * sizeof(T);
        std::free(p);
    }
    friend bool operator==(Counting, Counting) { return true; }
};

using Address = std::uint32_t;
using Tree = std::map<std::string, Address, std::less<>, Counting<std::pair<const std::string, Address>>>;
using Flat = std::flat_map<std::string, Address, std::less<>, std::vector<std::string, Counting<std::string>>,
                           std::vector<Address, Counting<Address>>>;
using Clock = std::chrono::steady_clock;

template <class F>
double time_ms(F work, long long& check) {
    auto start = Clock::now();
    check += work();
    std::chrono::duration<double, std::milli> took = Clock::now() - start;
    return took.count();
}

int main() {
    const int n = 50'000;
    std::vector<std::pair<std::string, Address>> symbols;
    for (int i = 0; i < n; ++i) symbols.emplace_back(std::format("fn_{:06}", (i * 7919) % 1'000'000), Address(i * 16));

    bytes = 0;
    Tree tree(symbols.begin(), symbols.end());
    std::size_t tree_bytes = bytes;
    bytes = 0;
    Flat flat(symbols.begin(), symbols.end());
    std::size_t flat_bytes = bytes;
    std::println("{} names of {} characters, sizeof(std::string) = {}", n, symbols[0].first.size(), sizeof(std::string));
    std::println("std::map:      {:>8} bytes, {:.1f} per entry", tree_bytes, double(tree_bytes) / n);
    std::println("std::flat_map: {:>8} bytes, {:.1f} per entry", flat_bytes, double(flat_bytes) / n);

    std::mt19937 random(5);
    std::vector<std::string> queries;
    for (int i = 0; i < 16'384; ++i) queries.push_back(symbols[random() % n].first);
    long long check = 0;
    double tree_find = 1e300, flat_find = 1e300, tree_scan = 1e300, flat_scan = 1e300;
    for (int round = 0; round < 15; ++round) {
        tree_find = std::min(tree_find, time_ms([&] { long long s = 0; for (const auto& q : queries) s += tree.find(q)->second; return s; }, check));
        flat_find = std::min(flat_find, time_ms([&] { long long s = 0; for (const auto& q : queries) s += flat.find(q)->second; return s; }, check));
        tree_scan = std::min(tree_scan, time_ms([&] { long long s = 0; for (const auto& [name, address] : tree) s += address; return s; }, check));
        flat_scan = std::min(flat_scan, time_ms([&] { long long s = 0; for (Address a : flat.values()) s += a; return s; }, check));
    }
    const double per_lookup = 1e6 / double(queries.size());  // milliseconds for all queries -> nanoseconds per query
    std::println("one lookup:     std::map {:7.1f} ns, std::flat_map {:7.1f} ns", tree_find * per_lookup, flat_find * per_lookup);
    std::println("one full pass:  std::map {:7.3f} ms, std::flat_map {:7.3f} ms", tree_scan, flat_scan);
    std::println("check: {}", check);
}
A read-only symbol table in std::map and in std::flat_map Python · read_heavy_session.py
from session import run

# read_heavy.cpp with -O2, with each compiler and its standard library.
run("""
clang++ -std=c++23 -O2 -Wall -Wextra read_heavy.cpp -o read_heavy
./read_heavy
g++-16 -std=c++23 -O2 -Wall -Wextra read_heavy.cpp -o read_heavy-gcc
./read_heavy-gcc
""")

Output

$ clang++ -std=c++23 -O2 -Wall -Wextra read_heavy.cpp -o read_heavy
$ ./read_heavy
50000 names of 9 characters, sizeof(std::string) = 24
std::map:       3200000 bytes, 64.0 per entry
std::flat_map:  1400000 bytes, 28.0 per entry
one lookup:     std::map   247.8 ns, std::flat_map   195.2 ns
one full pass:  std::map   0.810 ms, std::flat_map   0.005 ms
check: 796278449280
$ g++-16 -std=c++23 -O2 -Wall -Wextra read_heavy.cpp -o read_heavy-gcc
$ ./read_heavy-gcc
50000 names of 9 characters, sizeof(std::string) = 32
std::map:       3600000 bytes, 72.0 per entry
std::flat_map:  2359296 bytes, 47.2 per entry
one lookup:     std::map   293.7 ns, std::flat_map   190.6 ns
one full pass:  std::map   0.777 ms, std::flat_map   0.020 ms
check: 796278449280

This output changes from run to run: the times depend on the computer and on what else it is doing

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 read_heavy_session.py

  • Memory. With libc++, the std::map requested 64 bytes per entry: a 24-byte string and a 4-byte address, plus the node’s three pointers and colour, padded. The flat_map requested 28, exactly the string and the address, because libc++’s range constructor reserved the right size. With libstdc++ the strings are 32 bytes, the map needed 72 bytes per entry, and the flat_map 47.2: its vectors grew by doubling to room for 65,536 entries. The map also made one allocation per entry, while the flat_map allocated only its two vectors, a few times over while they grew.
  • Lookups. flat_map answered each lookup faster with both compilers, though not by a large factor: both containers compare the name with about 16 others, the base-2 logarithm of 50,000, and the flat version saves mostly the jumps from node to node.
  • A full pass over the values was at least 30 times faster with flat_map, because values() is one vector, which the processor reads at full speed, while the map’s pass visits 50,000 nodes scattered in memory.

The chart counts the work of one lookup as n doubles, for a binary search over sorted keys and, for comparison, a scan that checks one value after another. Pick the mark at 50,000:

Interactive · watch it grow Probes of a binary search and checks of a scan, up to a million keys n doubles at each step, from 1 up to 1,000,000, with 50,000 as steps too. Each mark counts what the algorithm did at that size; the dashed line is the count worked out by reasoning, drawn in full from the start.
Probes of a binary search and checks of a scan, up to a million keys: at n = 1, linear search checks 1 value, binary search makes 1 probe; dashed lines show the derived counts.Linear search · values checked (log scale) · dashed: nBinary search · probes · dashed: ⌊log₂ n⌋ + 1110010k1M010201101001k10k100k1Mn, the size of the input (log scale: n doubles at each step)n = 1
  • Linear search, measured (circles)
  • Binary search, measured (squares)
  • Derived count (dashed): n for linear search; ⌊log₂ n⌋ + 1 for binary search
  • The size in focus (ringed)

n = 1: linear search checks 1 value and binary search makes 1 probe. The dashed lines are the derived counts: n and ⌊log₂ n⌋ + 1.

From n = 1 to 1,000,000, searching for a value larger than every one, the counts grew: linear search from 1 to 1,000,000 values checked and binary search from 1 to 20 probes. Each matched the derived count at every size: n for linear search and ⌊log₂ n⌋ + 1 for binary search.

Size n 1
Linear search · values checked 1
Binary search · probes 1
Scan ÷ binary search 1×
Every measured count as a table
Measured at each size, searching for a value larger than every one
nLinear search: values checkedBinary search: probes
111
222
443
884
16165
32326
64647
1281288
2562569
51251210
1,0241,02411
2,0482,04812
4,0964,09613
8,1928,19214
16,38416,38415
32,76832,76816
50,00050,00016
65,53665,53617
131,072131,07218
262,144262,14419
524,288524,28820
1,000,0001,000,00020

At n = 50,000 the binary search makes 16 probes, the “about 16” comparisons of a lookup above, where a scan would check all 50,000 names. A std::map makes about as many comparisons, but each one first follows a pointer to a node.

The trade-offs are the ones the first lesson of this module listed: a std::map keeps its iterators and references valid while it changes and inserts in O(log n), while a flat container invalidates them on every insertion or erasure, and inserts in O(n). The standard says it plainly: the flat containers do not meet the associative containers’ requirements on iterator invalidation.

Key idea

For data that is built once and then read, a flat container stores little more than its elements, finds a key with the same number of comparisons as a tree, and walks every element at the speed of a vector.

Checkpoint

Check: Memory and speed for data that is mostly read

  1. Question 1 of 2 How many bytes per entry did the read-only symbol table request as a std::flat_map with libc++?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 28 bytes

    28 bytes: the 24-byte std::string and the 4-byte address, nothing more, because libc++'s range constructor reserved the right size. The std::map requested 64 bytes per entry, with a node per element.

  2. Question 2 of 2 A binary search over 50,000 sorted names, looking for one that is missing, makes how many probes?

    Type a number.

    A hint

    The chart's count for a missing value is ⌊log₂ n⌋ + 1.

    Show the answer: Question 2 of 2

    Answer: 16 probes

    ⌊log₂ 50,000⌋ + 1 = 15 + 1 = 16, the chart's count at n = 50,000. A flat_map and a std::map both compare the name with about 16 others; the flat_map saves the jumps from node to node.

Two promises the flat containers trust you to keep

Bulk loading is fast because the flat containers trust you. Two programs show what happens when the trust is misplaced:

broken_promise.cpp C++ · broken_promise.cpp
// std::sorted_unique is a promise that the keys are sorted and contain no duplicates. Nothing checks it in an
// ordinary build, and a false promise is undefined behaviour: here the keys are not sorted, so binary searches
// look in the wrong half.
#include <flat_map>
#include <print>
#include <vector>

int main() {
    std::vector<int> keys{10, 30, 20, 40};  // not sorted
    std::vector<int> values{1, 3, 2, 4};
    std::flat_map<int, int> m(std::sorted_unique, std::move(keys), std::move(values));
    std::println("{}", m);
    std::println("contains(20): {}, contains(30): {}", m.contains(20), m.contains(30));
}
duplicates.cpp C++ · duplicates.cpp
// Which value survives when the input repeats a key? std::map's range constructor inserts the pairs in order and
// keeps the first value of each key. flat_map's range constructor sorts the pairs by key, and that sort does not
// have to keep equal keys in their input order, so the value it keeps is not necessarily the first.
#include <cstddef>
#include <flat_map>
#include <map>
#include <print>
#include <random>
#include <utility>
#include <vector>

int main() {
    std::vector<std::pair<int, int>> few{{1, 10}, {2, 20}, {1, 11}, {3, 30}, {1, 12}, {2, 21}};
    std::println("six pairs: std::map {}, std::flat_map {}",
                 std::map<int, int>(few.begin(), few.end()), std::flat_map<int, int>(few.begin(), few.end()));

    // 2,000 pairs with 100 different keys; each value is the pair's position, so the first value is the smallest.
    std::mt19937 random(1);
    std::vector<std::pair<int, int>> rows;
    for (int i = 0; i < 2000; ++i) rows.emplace_back(int(random() % 100), i);
    std::map<int, int> tree(rows.begin(), rows.end());
    std::flat_map<int, int> flat(rows.begin(), rows.end());
    std::size_t different = 0;
    for (auto [key, value] : tree)
        if (flat.at(key) != value) ++different;
    std::println("2000 pairs, 100 keys: the flat_map kept another value than the first for {} keys", different);
}
A false sorted_unique, then duplicates in the input Python · promises_session.py
from session import run

# broken_promise.cpp in an ordinary build, then in each library's debug mode, which checks the promise; grep keeps
# the line that names the problem. Then duplicates.cpp with both libraries.
run("""
clang++ -std=c++23 -Wall -Wextra broken_promise.cpp -o broken_promise && ./broken_promise
clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG broken_promise.cpp -o broken_promise-debug
./broken_promise-debug 2>&1 | grep -o "libc++ Hardening assertion.*"
g++-16 -std=c++23 -D_GLIBCXX_DEBUG broken_promise.cpp -o broken_promise-gcc-debug
./broken_promise-gcc-debug 2>&1 | grep -o "Assertion .*"
clang++ -std=c++23 -O2 -Wall -Wextra duplicates.cpp -o duplicates && ./duplicates
g++-16 -std=c++23 -O2 -Wall -Wextra duplicates.cpp -o duplicates-gcc && ./duplicates-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra broken_promise.cpp -o broken_promise && ./broken_promise
{10: 1, 30: 3, 20: 2, 40: 4}
contains(20): false, contains(30): false
$ clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG broken_promise.cpp -o broken_promise-debug
$ ./broken_promise-debug 2>&1 | grep -o "libc++ Hardening assertion.*"
libc++ Hardening assertion __is_sorted_and_unique(__containers_.keys) failed: Either the key container is not sorted or it contains duplicates
$ g++-16 -std=c++23 -D_GLIBCXX_DEBUG broken_promise.cpp -o broken_promise-gcc-debug
$ ./broken_promise-gcc-debug 2>&1 | grep -o "Assertion .*"
Assertion 'ranges::is_sorted(_M_cont.keys, _M_comp)' failed.
$ clang++ -std=c++23 -O2 -Wall -Wextra duplicates.cpp -o duplicates && ./duplicates
six pairs: std::map {1: 10, 2: 20, 3: 30}, std::flat_map {1: 10, 2: 20, 3: 30}
2000 pairs, 100 keys: the flat_map kept another value than the first for 95 keys
$ g++-16 -std=c++23 -O2 -Wall -Wextra duplicates.cpp -o duplicates-gcc && ./duplicates-gcc
six pairs: std::map {1: 10, 2: 20, 3: 30}, std::flat_map {1: 10, 2: 20, 3: 30}
2000 pairs, 100 keys: the flat_map kept another value than the first for 93 keys

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 promises_session.py

  • std::sorted_unique must be true. The keys 10, 30, 20, 40 are not sorted, and the ordinary build accepted them. The map then printed its keys out of order and could find neither 20 nor 30, although both were there: every binary search assumed an order that did not exist. The standard makes this undefined behaviour. Both debug modes check the promise: libc++’s says “Either the key container is not sorted or it contains duplicates”, and libstdc++’s fails an is_sorted assertion.
  • The range constructor keeps one value per key, but not necessarily the first. For six pairs, both containers kept the first value of each key. For 2,000 pairs with 100 keys, the flat_map kept another value than the first for 95 keys with libc++ and 93 with libstdc++. std::map inserts the pairs one after another and refuses a key it already has, so it always keeps the first; the flat containers sort the pairs, and the standard does not require that sort to keep equal keys in their input order.

Step through a search for 30 in the broken map’s keys, halving the range as std::lower_bound does, and see why 30 is missed:

Interactive · step by step A binary search over keys that are not sorted Step through a search for 30 in the four keys, read left to right and top to bottom. A key's sub-label says what the search decided about it.
A binary search over keys that are not sorted, step 4 of 4. Showing position 0: 10 (ruled out), position 1: 30 (ruled out), position 2: 20 (read: 20 < 30), position 3: 40 (read: 40, not 30), contains(30) (false: 30 not found). In focus: position 1: 30, contains(30).position 0: 10ruled outposition 1: 30ruled outposition 2: 20read: 20 < 30position 3: 40read: 40, not 30contains(30)false: 30 not foundnever read

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. A promise that is false. std::sorted_unique promised that the keys 10, 30, 20, 40 are sorted. They are not, because 30 comes before 20, and nothing checked the promise in an ordinary build.
  2. The first probe. A binary search halves the range. It reads position 2 first: 20 is less than 30, and in sorted keys everything up to it would be smaller too, so positions 0 to 2 are ruled out, 30 among them.
  3. The second probe. Position 3 holds 40, which is not less than 30, so in sorted keys 30 would have to be right here. It is not: position 3 holds 40.
  4. Not found. contains(30) returns false, although 30 is at position 1, which the search never read. The program printed contains(20): false, contains(30): false with both libraries: a false promise is undefined behaviour.

When the input can repeat a key and it matters which value wins, decide it yourself before the map sees the data, which is the exercise below.

Checkpoint

Check: The two promises

  1. One question The keys handed to a std::flat_map with std::sorted_unique are 10, 30, 20, 40. What happens in an ordinary build?

    Choose one answer.

    Show the answer: One question

    Answer: Nothing checks the promise; the program has undefined behaviour, and lookups can miss keys that are there

    std::sorted_unique is a promise that the keys are sorted and contain no duplicates. A false one is undefined behaviour: every binary search assumes an order that does not exist. Both debug modes check the promise.

Practise: a read-only symbol table

Write build_symbol_table(rows), which builds a std::flat_map from name to address. The rows arrive in any order, and when a name appears in several rows, the table keeps the address of its first row. Then write address_of, which returns the address of a name, or std::nullopt.

The starter code and its sample tests

C header · symbols.h

// Starter code for the exercise: a read-only symbol table, built once from rows that arrive in any order, then only
// read. When a name appears in several rows, the table keeps the address of its first row.
#pragma once
#include <cstdint>
#include <flat_map>
#include <optional>
#include <string>
#include <utility>
#include <vector>

using SymbolTable = std::flat_map<std::string, std::uint64_t>;

inline SymbolTable build_symbol_table(std::vector<std::pair<std::string, std::uint64_t>> rows) {
    // TODO: sort the rows by name, keeping equal names in their input order, keep the first row of each name, and
    // hand the two vectors to the table with std::sorted_unique
    (void)rows;
    return {};
}

inline std::optional<std::uint64_t> address_of(const SymbolTable& table, const std::string& name) {
    // TODO
    (void)table;
    (void)name;
    return std::nullopt;
}

C++ · symbols_tests.cpp

// Sample tests for symbols.h. Build: clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra symbols_tests.cpp -o symbols_tests
#include <cstdint>
#include <format>
#include <map>
#include <optional>
#include <print>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "symbols.h"

int checks = 0;
int failures = 0;

void check(bool ok, const char* what) {
    ++checks;
    if (!ok) {
        ++failures;
        std::println("FAIL {}", what);
    }
}

int main() {
    SymbolTable t = build_symbol_table({{"main", 0x1000}, {"init", 0x2000}, {"exit", 0x3000}, {"init", 0x4000}});
    check(t.size() == 3, "three different names");
    check(t.keys() == std::vector<std::string>{"exit", "init", "main"}, "the names are sorted");
    check(address_of(t, "init") == 0x2000, "a repeated name keeps the address of its first row");
    check(address_of(t, "main") == 0x1000, "a name that appears once");
    check(!address_of(t, "free").has_value(), "a missing name");
    check(build_symbol_table({}).empty(), "no rows, an empty table");

    // 20,000 rows with 2,000 different names, compared with a std::map that keeps the first row of each name.
    std::mt19937 random(4);
    std::vector<std::pair<std::string, std::uint64_t>> rows;
    std::map<std::string, std::uint64_t> expected;
    for (std::uint64_t i = 0; i < 20'000; ++i) {
        std::string name = std::format("sym{}", random() % 2'000);
        rows.emplace_back(name, i);
        expected.try_emplace(name, i);
    }
    SymbolTable big = build_symbol_table(rows);
    bool same = big.size() == expected.size();
    for (const auto& [name, address] : expected) same = same && address_of(big, name) == address;
    check(same, "20,000 rows: every name keeps the address of its first row");

    std::println("{} of {} checks passed", checks - failures, checks);
    return failures == 0 ? 0 : 1;
}
The sample tests against the starter code Python · symbols_session.py
from session import run

# The sample tests run against the starter code, before any TODO is done, with the sanitizers switched on.
run("""
clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra symbols_tests.cpp -o symbols_tests && ./symbols_tests
g++-16 -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra symbols_tests.cpp -o symbols_tests-gcc && ./symbols_tests-gcc
""")

Output

$ clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra symbols_tests.cpp -o symbols_tests && ./symbols_tests
FAIL three different names
FAIL the names are sorted
FAIL a repeated name keeps the address of its first row
FAIL a name that appears once
FAIL 20,000 rows: every name keeps the address of its first row
2 of 7 checks passed
[exit status 1]
$ g++-16 -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra symbols_tests.cpp -o symbols_tests-gcc && ./symbols_tests-gcc
FAIL three different names
FAIL the names are sorted
FAIL a repeated name keeps the address of its first row
FAIL a name that appears once
FAIL 20,000 rows: every name keeps the address of its first row
2 of 7 checks passed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 symbols_session.py

You are done when both compilers print 7 of 7 checks passed. Hints: std::ranges::stable_sort with the projection &std::pair<std::string, std::uint64_t>::first sorts the rows by name and keeps equal names in their input order; then copy the first row of each name into two vectors and hand them to the table with std::sorted_unique. Passing the rows straight to the range constructor passes every check but the last, which compares 20,000 rows with a std::map that keeps each first row.

Checkpoint

Check: The two promises

  1. One question In the exercise, why sort the rows with std::ranges::stable_sort rather than std::ranges::sort?

    Choose one answer.

    Show the answer: One question

    Answer: stable_sort keeps rows with equal names in their input order, so the first row of each name stays first

    std::ranges::sort does not keep equal elements in their input order, and neither does the flat_map's own sort. stable_sort does, so after it the first row of each name is the first of its run, ready for std::sorted_unique.

When the seven checks pass, test yourself on the two vectors, the proxy pairs, the cost of an insertion and the two promises, with questions that adapt to your answers and a reason behind every option:

Practice that adapts to you

Practise this lesson

16 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 16 What does stock.keys() return for a std::flat_map<std::string, int>?

    Choose one answer.

    Show the answer: Question 1 of 16

    Answer: The vector of keys itself, read-only

    keys() and values() return the two vectors themselves, read-only: ["clips", "paper", "pens"] and [120, 500, 40] in the example.

  2. Question 2 of 16 std::flat_set<int> marks{72, 91, 64, 91}; What does the set hold?

    Choose one answer.

    Show the answer: Question 2 of 16

    Answer: {64, 72, 91}

    A flat_set is a flat_map without values: one sorted vector of unique keys. The program printed {64, 72, 91} and found 72 as the first mark at least 70.

  3. Question 3 of 16 Which of these loops over a std::flat_map compile?

    Choose every answer that is right.

    Show the answer: Question 3 of 16

    Answer:

    • for (auto&& [k, v] : fm)
    • for (const auto& [k, v] : fm)
    • for (auto [k, v] : fm)

    Each element of a flat_map is a temporary pair of references. auto, const auto& and auto&& all accept it; only a non-const auto& is refused, which is the error code moving from std::map meets first.

  4. Question 4 of 16 Why does a std::flat_map have no std::pair objects inside it?

    Choose one answer.

    Show the answer: Question 4 of 16

    Answer: Its keys and values live in two separate vectors, so a pair can only be built on the spot

    A flat_map's element at position i is made of the key at position i of one vector and the value at position i of the other, so dereferencing an iterator builds a std::pair of two references, a proxy object.

  5. Question 5 of 16 About how many keys does loading n keys in random order, one emplace at a time, shift in all?

    Choose one answer.

    Show the answer: Question 5 of 16

    Answer: About n²/4, because each new key lands, on average, in the middle of the keys already stored

    The i-th insertion shifts about i/2 keys on average, so n insertions shift about n²/4 in all: quadratic in n. The range constructor avoids it by sorting once.

  6. Question 6 of 16 What does erasing a key from the middle of a std::flat_map cost?

    Choose one answer.

    Show the answer: Question 6 of 16

    Answer: O(n), because every later key and value moves down one place

    A single insertion or erasure takes linear time in a flat container, and the standard lists that as one of the ways the flat containers differ from the other associative containers.

  7. Question 7 of 16 What does passing std::sorted_unique to a std::flat_map constructor tell it?

    Choose one answer.

    Show the answer: Question 7 of 16

    Answer: That the keys are already sorted and contain no duplicates, so it can take the containers as they are

    std::sorted_unique is a tag that promises the input keys are sorted and unique. The map trusts it and takes the two vectors as they are; the same promise holds for replace(keys, values).

  8. Question 8 of 16 A program must change many keys of a std::flat_map at once. Which approach does the lesson give?

    Choose one answer.

    Show the answer: Question 8 of 16

    Answer: Take the containers out with std::move(fm).extract(), change them, and put them back with replace(keys, values)

    extract hands the two containers over, the program changes them, keeping the keys sorted and unique, and replace puts them back without sorting or checking.

  9. Question 9 of 16 Using the standard's bound N + M log₂ M, about how many steps does adding M = 1,024 new keys to a flat_map of N = 1,000,000 cost?

    Type a number.

    A hint

    log₂ 1,024 is 10.

    Show the answer: Question 9 of 16

    Answer: 1010240 steps (anything from 990240 to 1030240 counts)

    1,000,000 + 1,024 × 10 = 1,010,240: one pass over the map, plus one sort of the new keys. Inserting the same keys one at a time would shift about half a million elements for each of them.

  10. Question 10 of 16 How did a full pass over the 50,000 values compare between std::map and std::flat_map?

    Choose one answer.

    Show the answer: Question 10 of 16

    Answer: The flat_map was at least 30 times faster, because values() is one vector read at full speed

    A pass over a vector reads memory in order, which the processor does at full speed; a pass over a tree follows a pointer to a scattered node for every element.

  11. Question 11 of 16 std::flat_map answered each lookup faster than std::map, but not by a large factor. Why so little?

    Choose one answer.

    Show the answer: Question 11 of 16

    Answer: Both compare the name with about 16 others; the flat map saves mostly the jumps from node to node

    A binary search over the flat_map's keys and a walk down the map's tree make about the same number of comparisons. The flat_map's are over contiguous memory, which helps, but the full pass, which reads every element, gains far more.

  12. Question 12 of 16 With libstdc++, the flat_map requested 47.2 bytes per entry for 50,000 entries, although a string and an address take 36. Why?

    Choose one answer.

    Show the answer: Question 12 of 16

    Answer: Its vectors grew by doubling to room for 65,536 entries; 65,536 × 36 bytes is 2,359,296

    The vectors' capacity, not their size, is what was requested: 65,536 slots of a 32-byte string and a 4-byte address. Reserving the final size first, or building from vectors of the right size, removes the spare room.

  13. Question 13 of 16 When is a std::flat_map a better choice than a std::map?

    Choose every answer that is right.

    Show the answer: Question 13 of 16

    Answer:

    • Memory per element matters
    • The program often walks over every element
    • The map is built once and then mostly read

    Contiguous storage makes lookups and full passes faster and saves the node overhead of every element. Each insertion or erasure, though, shifts elements and invalidates iterators and references into the map, which a std::map never does to the elements it keeps.

  14. Question 14 of 16 Rows repeat some keys, and the map must keep the first value of each. Which approach does that with every standard library?

    Choose one answer.

    Show the answer: Question 14 of 16

    Answer: std::ranges::stable_sort by key, keep the first row of each key, then build the map with std::sorted_unique

    The range constructor and insert(first, last) sort without promising to keep equal keys in input order, and in the lesson's run they kept a later value for 95 and 93 of 100 keys. stable_sort keeps the input order of equal keys, so the first row of each key is first in its run. sorted_unique on unsorted rows is undefined behaviour.

  15. Question 15 of 16 What did the map built with a false std::sorted_unique print?

    Choose one answer.

    Show the answer: Question 15 of 16

    Answer: Its keys out of order, and contains false for 20 and for 30, both of which it held

    With keys 10, 30, 20, 40 the binary searches looked in the wrong half, so contains(20) and contains(30) were both false. Both libraries' debug modes caught the broken promise.

  16. Question 16 of 16 What catches a false std::sorted_unique promise?

    Choose one answer.

    Show the answer: Question 16 of 16

    Answer: The libraries' debug modes, libc++'s debug hardening mode and libstdc++'s -D_GLIBCXX_DEBUG

    Both debug modes check the promise: libc++'s reported "Either the key container is not sorted or it contains duplicates", and libstdc++'s failed an is_sorted assertion. Use them in test builds.

Interview questions

Fresher · What is std::flat_map, and when would you choose it over std::map?

std::flat_map (C++23) is a sorted associative container with the interface of std::map, built on two sorted sequence containers, by default vectors: one holds the keys and the other the values at the same positions. Lookups are binary searches over contiguous memory, iteration is as fast as over a vector, and there is no per-element node, so it uses much less memory. But inserting or erasing a key shifts the later elements, which takes linear time, and invalidates iterators and references into the map. Choose it for data that is built once, or changed rarely and in bulk, and then read many times, such as a lookup table loaded at start-up. Keep std::map when keys are inserted and erased all the time, or when other code holds references to elements while the map changes.

Two quick follow-ups test the details: the cost of an erasure at the front, and the order of a loop. Decide both:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: a std::flat_map holds 1,000,000 keys. How many keys move when its first key is erased?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 999999 keys

    Every key after the erased one moves down one place, and so does every value: 999,999 of each. An erasure is linear like an insertion, which is why flat containers suit data that rarely changes.

  2. Question 2 of 2 Follow-up: in which order does a loop over a std::flat_map visit its elements?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: In key order, like std::map

    A flat_map is a sorted associative container with the interface of std::map, so iteration follows the comparator, std::less by default. Printing it with std::println showed the keys in alphabetical order.

Replacing a container is a decision interviewers like to probe further. The module’s bank has two such questions on flat containers, a configuration service and a sorted vector of blocked users:

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    A configuration service loads 200,000 settings at start-up, serves 50,000 reads a second, and applies a batch of changes every few minutes. A teammate proposes replacing std::map<std::string, std::string> with std::flat_map. Estimate what changes in memory and lookup cost, and say what would make you reject the change.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    Your code keeps the ids of blocked users in a sorted std::vector<std::uint64_t> and calls std::ranges::binary_search on it. A teammate suggests std::flat_set instead. What would actually change in speed, memory, safety and code, and which do you choose?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A flat_map is two sorted vectors, keys and values, with the interface of std::map; a flat_set is one. Both ship with Apple clang 21’s libc++ and with GCC 16.
  • Lookups are O(log n) binary searches over contiguous memory, and a full pass is as fast as a vector’s; one insertion or erasure is O(n) and invalidates iterators and references.
  • Its iterators return a temporary pair of references, so loop with auto [k, v], const auto& or auto&&, never auto&.
  • Load in bulk: inserting 20,000 keys one at a time shifted about 100 million elements, while the range constructor sorts once, and std::sorted_unique takes data that is already sorted as it is.
  • For a read-only table of 50,000 names, the flat map requested 28 bytes per entry with libc++ against the map’s 64, and a full pass over its values was at least 30 times faster.
  • sorted_unique is a promise nobody checks outside the debug modes, and the range constructor may keep any of several values for a repeated key: with 2,000 rows, 95 of 100 keys kept a later value with libc++.

Terms in this lesson

binary search
A search of a sorted sequence that compares the target with the middle element and keeps only the half that can hold it, so n elements need at most about log2 n + 1 probes: 20 for a million. std::lower_bound and the flat containers' lookups work this way.
flat container
std::flat_map, std::flat_set or one of their multi versions (C++23): an adaptor that keeps its keys sorted in a sequence container, std::vector by default, and a flat_map's values in a second one, so lookups are binary searches and insertions shift elements.
std::sorted_unique
A tag passed to a flat container's constructor, insert or replace that promises the keys are already sorted and contain no duplicates, so the container takes them as they are. Nothing checks it outside the debug modes, and a false promise is undefined behaviour.

References

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.