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

Choosing a C++ container: complexity and speed

Match tasks to the right C++ standard container from its complexity guarantees, then check the choice with memory and lookup timings on two compilers.

  • 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

  • Match common tasks to the right standard container
  • Explain the complexity guarantees of each container
  • Estimate the bytes each container uses per element
  • Benchmark containers with an optimised build, real data and repeated runs
  • Justify container choices with measurements

Before you start

Holding the same 100,000 int values, a std::vector asked for about 5 bytes per element and a std::set for 32 or 40, depending on the library. The C++ standard library offers more than a dozen containers, and choosing one comes down to two questions: which operations does your program perform most often, and which guarantees does it need? Start with std::vector. Its elements sit next to each other in one block of memory, so it is the fastest container to loop over and to index, and adding at the end takes amortised constant time: A cost that is constant on average over a long run of calls, although one call may take much longer. A push_back sometimes moves every element, but because the capacity doubles, 1,000 calls moved 1,023 elements in all. More in “std::vector: the container to reach for first”. Choose another container when an operation that a vector does badly dominates the work, such as adding at the front or finding values by key in a large collection, or when you need a guarantee that a vector cannot give: keys kept in sorted order, or references that stay valid while elements are added.

Below, you sort the containers into families, read their cost guarantees and measure what the guarantees leave out.

Four families, told apart by how they store elements

Every standard container owns its elements: it creates them, keeps them and destroys them. How it stores them is what sets the families apart:

  • sequence container: A container that keeps its elements in the order they were put in: std::array and std::vector in one block, std::deque in fixed-size blocks, std::list and std::forward_list in one node per element., array, vector, deque, list and forward_list, keep the elements in the order you put them: in one block (array, vector), in fixed-size blocks (deque) or in one node per element (list, forward_list).
  • ordered associative container: std::set, std::map, std::multiset or std::multimap: a container that keeps its elements sorted by key, one node per element, in a balanced tree, so that finding, inserting and erasing a key take O(log n)., set, map, multiset and multimap, keep them sorted by key, one node per element, in a balanced tree.
  • unordered associative container: std::unordered_set, std::unordered_map or one of their multi versions: a hash table that picks a bucket for each element from a hash of its key, so that lookups take constant time on average, and lists its elements in an unspecified order., unordered_set, unordered_map, unordered_multiset and unordered_multimap, keep them in buckets chosen by a hash of the key, one node per element.
  • container adaptor: A class template that keeps its elements in another container and offers a narrower or different interface: std::stack and std::queue on a std::deque by default, std::priority_queue on a std::vector, and the C++23 flat containers on sorted vectors., stack, queue and priority_queue, and since C++23 flat_set, flat_map, flat_multiset and flat_multimap, keep them inside other containers, behind a narrower or different interface.

Step through the families one at a time, and watch where each keeps its elements and which container an adaptor keeps them in:

Interactive · step by step Where each family keeps its elements Step through the families. Each box names the containers of one kind and how they hold their elements; an arrow shows a container that another one keeps its elements in.
Where each family keeps its elements, step 7 of 7. Showing vector, array, flat_set, flat_map …, deque, stack, queue, list, forward_list, set, map, multi…, unordered_set, _map …. In focus: stack, queue, deque.kept in vectorsa deque by defaultvector, arrayone block, side by sideflat_set, flat_map …sorted vectors insidedequefixed-size blocks, an indexstack, queueanother container insidelist, forward_lista node per elementset, map, multi…nodes in a balanced treeunordered_set, _map …buckets of chained nodes

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

Every step as text
  1. One block. std::array and std::vector keep their elements side by side in one block of memory, in the order you put them. An array's size is fixed when the program is compiled; a vector grows.
  2. Blocks and an index. std::deque keeps its elements in blocks of a fixed size and finds them through an index of pointers to the blocks, so it can grow at the front and at the back.
  3. A node each. std::list and std::forward_list give every element a node of its own, linked to the next node, and in a list to the previous one too. These are the last of the sequence containers.
  4. Sorted in a tree. set, map, multiset and multimap keep their elements sorted by key, one node per element, in a balanced tree. libc++ and libstdc++ both build it as a red-black tree.
  5. Hashed into buckets. The four unordered containers compute a hash of each key, use it to pick one of many buckets, and keep the elements of a bucket in a chain of nodes. The keys are in no particular order.
  6. Flat containers. flat_set, flat_map and their multi versions, new in C++23, are adaptors: they keep their elements in other containers, std::vector by default, sorted. A flat_map uses one vector for its keys and another for its values.
  7. The older adaptors. std::stack and std::queue keep their elements in a std::deque by default, and std::priority_queue in a std::vector, behind a narrower interface: push, pop and a look at the next element out.

The arrows of the last two steps are the point to keep: an adaptor stores nothing itself, so what it costs is what the container inside it costs. A few details matter later:

  • The multi versions allow several elements with the same key; the others keep each key once.
  • The standard never says “red-black tree” or “hash table”. It specifies each operation’s cost and which iterators and references stay valid, and those rules are hard to meet any other way: libc++ and libstdc++ both build std::map as a red-black tree: A binary search tree that marks each node red or black and recolours and rotates nodes on every insertion and erasure to stay balanced, so that a lookup visits O(log n) nodes. libc++ and libstdc++ build std::map and std::set as red-black trees. and std::unordered_map as an array of buckets, each holding a chain of nodes.
  • The flat containers are adaptors because they keep their elements in other containers, by default std::vectors kept in sorted order. A flat_map uses one vector for the keys and another for the values.
  • std::span and std::string_view look like containers but are views: they refer to elements that something else owns.

Checkpoint

Check: The four families of containers

  1. Question 1 of 2 Which family of containers does std::flat_map belong to?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The container adaptors, because it keeps its elements in other containers

    flat_set, flat_map and their multi versions are adaptors, like stack and queue: they keep their elements inside other containers, sorted std::vectors by default, and offer an associative interface on top. A flat_map uses one vector for the keys and one for the values.

  2. Question 2 of 2 A function takes a std::span<const int> that refers to the elements of a std::vector<int>. What does the span own?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Nothing; it refers to elements that the vector owns

    Every standard container owns its elements. std::span and std::string_view look like containers but only refer to elements that something else owns, so they must not outlive it.

The standard promises costs, not data structures

The standard states the cost of every container operation as an upper bound on the work it does: comparisons, hash calls, copies or moves of elements. Two words in it need care. Amortised means averaged over a long run of calls: one push_back on a full vector moves every element, but doubling the capacity keeps the average cost per call constant. On average, for the unordered containers, assumes a hash function that spreads the keys over the buckets; when many keys share a bucket, a lookup compares the key with each of them, and the worst case is linear.

For the sequence containers:

  • Element at position i: O(1) in a vector and a deque; O(i) in a list, which has to walk from one end.
  • Add or remove at the back: O(1) amortised in a vector; O(1) in a deque and a list.
  • Add or remove at the front: O(n) in a vector; O(1) in a deque and a list.
  • Insert or erase in the middle: O(n) in a vector, whose later elements move, and in a deque, whose nearer end moves; O(1) in a list, once you hold an iterator to the place.
  • Find a value: O(n) in all three, or O(log n) with a binary search when a vector or deque is sorted.

For the containers that look up by key:

  • Find a key: O(log n) in a map or set and in a flat_map or flat_set; O(1) on average and O(n) at worst in an unordered_map or unordered_set.
  • Insert a key: O(log n) in a map; O(1) on average and O(n) at worst in an unordered_map; O(n) in a flat_map, whose later elements move.
  • Erase at an iterator: O(1) amortised in a map; O(1) on average in an unordered_map; O(n) in a flat_map.
  • Visit the elements in key order: a map and a flat_map always list them in order; an unordered_map lists them in an unspecified order.
  • Find the nearest key with lower_bound: O(log n) in a map and a flat_map; an unordered_map has no such function.

Four of these lines are worth reading twice:

  • A vector has no push_front. The standard gives sequence containers push_front, push_back, operator[] and its other optional operations only where they take amortised constant time. Adding at the front of a vector moves every element, so the function does not exist; v.insert(v.begin(), x) still works, in linear time.
  • A list inserts in constant time only once you hold an iterator to the place. Finding the place is a walk, which is linear, as a measurement below shows.
  • A flat_map finds a key in O(log n), like a map, but inserts in O(n), because its keys sit sorted in a vector and every later key has to move to make room. The standard lists linear-time insertion and erasure of a single element as one of the ways the flat containers differ from the other associative containers.
  • Big-O hides the constant factor. O(1) for a hash lookup includes computing the hash and following a pointer or two; O(log n) for a sorted vector is about 20 comparisons for a million elements, all inside one block of memory. The rest of the lesson measures what that means.

The chart counts what finding a value costs as n doubles: the values a scan from the front checks, one per value, and the probes of a binary search over sorted values, counted on a real run of its loop. Press Play, or pick a size near the two marks:

Interactive · watch it grow Values a scan checks and probes a binary search makes, as n doubles n doubles at each step, from 1 up to 1,000,000,000, with 1,000 and 1,000,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.
Values a scan checks and probes a binary search makes, as n doubles: 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⌋ + 111k1M1B0102030401101001k10k100k1M10M100M1Bn, 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,000, searching for a value larger than every one, the counts grew: linear search from 1 to 1,000,000,000 values checked and binary search from 1 to 30 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,0001,00010
1,0241,02411
2,0482,04812
4,0964,09613
8,1928,19214
16,38416,38415
32,76832,76816
65,53665,53617
131,072131,07218
262,144262,14419
524,288524,28820
1,000,0001,000,00020
1,048,5761,048,57621
2,097,1522,097,15222
4,194,3044,194,30423
8,388,6088,388,60824
16,777,21616,777,21625
33,554,43233,554,43226
67,108,86467,108,86427
134,217,728134,217,72828
268,435,456268,435,45629
536,870,912536,870,91230
1,000,000,0001,000,000,00030

At n = 1,000 the scan checks 1,000 values and the binary search makes 10 probes; at n = 1,000,000 it is 1,000,000 against 20, the “about 20 comparisons” of the last line above. Both are guarantees about counts. How long each step takes is a different question, and the next sections measure it.

Key idea

The standard promises how much work each operation does and which iterators survive it, not how the container is built: map is O(log n), unordered_map O(1) on average and O(n) at worst, and flat_map finds in O(log n) but inserts in O(n).

Checkpoint

Check: Cost guarantees and their limits

  1. Question 1 of 2 One push_back on a full std::vector moves every element. Why does the standard still promise constant time for push_back?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The promise is amortised; doubling the capacity keeps the average cost per call constant over a long run

    Amortised means averaged over a long run of calls. A full buffer makes one push_back move every element, but because the capacity doubles, the moves of all the reallocations together stay below the final capacity.

  2. Question 2 of 2 A std::flat_map holds 100,000 keys, and a new key arrives that sorts before all of them. What does inserting it cost?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: O(n), because all 100,000 keys and their values move up one place

    A flat_map finds a key in O(log n), like a map, but inserts in O(n): its keys are sorted in a vector, and every key after the new one has to move. Here that is every key, and every value in the second vector too.

Node-based containers spend 16 to 40 bytes on a 4-byte int

These costs count operations, not bytes. This program fills seven containers with the same 100,000 int values and asks each one, through an allocator that counts, how much memory it requested:

memory.cpp C++ · memory.cpp
// What seven containers ask the allocator for while each holds the same 100,000 ints.
// Counting<T> is an allocator that adds up the bytes the container holds at the end and how many times it allocated;
// every standard container accepts an allocator as its last template argument.
#include <cstddef>
#include <cstdlib>
#include <deque>
#include <flat_set>
#include <forward_list>
#include <functional>
#include <list>
#include <new>
#include <print>
#include <set>
#include <unordered_set>
#include <vector>

struct Usage {
    std::size_t bytes = 0;        // bytes allocated and not yet freed
    std::size_t allocations = 0;  // calls to allocate, including buffers that were freed again
};
inline Usage usage;

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) {
        usage.bytes += n * sizeof(T);
        ++usage.allocations;
        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 {
        usage.bytes -= n * sizeof(T);
        std::free(p);
    }
    friend bool operator==(Counting, Counting) { return true; }
};

template <class Container>
void measure(const char* name, int n) {
    usage = {};
    Container c;
    for (int i = 0; i < n; ++i) {
        if constexpr (requires { c.push_back(i); }) c.push_back(i);
        else if constexpr (requires { c.push_front(i); }) c.push_front(i);  // forward_list has no push_back
        else c.insert(i);
    }
    long long total = 0;
    for (int x : c) total += x;  // use the elements, so the compiler keeps every allocation
    std::println("{:<14} {:>9} {:>8.1f} {:>12} {:>14}", name, usage.bytes, double(usage.bytes) / n, usage.allocations, total);
}

int main() {
    const int n = 100'000;
    std::println("{} ints of {} bytes each", n, sizeof(int));
    std::println("{:<14} {:>9} {:>8} {:>12} {:>14}", "container", "bytes", "per int", "allocations", "sum (a check)");
    measure<std::vector<int, Counting<int>>>("vector", n);
    measure<std::deque<int, Counting<int>>>("deque", n);
    measure<std::list<int, Counting<int>>>("list", n);
    measure<std::forward_list<int, Counting<int>>>("forward_list", n);
    measure<std::set<int, std::less<int>, Counting<int>>>("set", n);
    measure<std::unordered_set<int, std::hash<int>, std::equal_to<int>, Counting<int>>>("unordered_set", n);
    measure<std::flat_set<int, std::less<int>, std::vector<int, Counting<int>>>>("flat_set", n);
}
Bytes requested by each container, with libc++ and libstdc++ Python · memory_session.py
from session import run

# memory.cpp built and run with Apple clang and libc++, then with GCC 16 and libstdc++: the two libraries lay out
# their nodes and buckets differently, so the numbers differ where the containers allocate nodes. The first command
# asks the processor for the size of its cache lines, the blocks in which it reads memory.
run("""
/usr/sbin/sysctl -n hw.cachelinesize
clang++ -std=c++23 -O2 -Wall -Wextra memory.cpp -o memory
./memory
g++-16 -std=c++23 -O2 -Wall -Wextra memory.cpp -o memory-gcc
./memory-gcc
""")

Output

$ /usr/sbin/sysctl -n hw.cachelinesize
128
$ clang++ -std=c++23 -O2 -Wall -Wextra memory.cpp -o memory
$ ./memory
100000 ints of 4 bytes each
container          bytes  per int  allocations  sum (a check)
vector            524288      5.2           18     4999950000
deque             402432      4.0          106     4999950000
list             2400000     24.0       100000     4999950000
forward_list     1600000     16.0       100000     4999950000
set              3200000     32.0       100000     4999950000
unordered_set    3223016     32.2       100016     4999950000
flat_set          524288      5.2           18     4999950000
$ g++-16 -std=c++23 -O2 -Wall -Wextra memory.cpp -o memory-gcc
$ ./memory-gcc
100000 ints of 4 bytes each
container          bytes  per int  allocations  sum (a check)
vector            524288      5.2           18     4999950000
deque             410608      4.1          790     4999950000
list             2400000     24.0       100000     4999950000
forward_list     1600000     16.0       100000     4999950000
set              4000000     40.0       100000     4999950000
unordered_set    2983464     29.8       100014     4999950000
flat_set          524288      5.2           18     4999950000

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

An int takes 4 bytes, so 4 bytes per element would mean no overhead at all. The numbers here are evidence from one machine, not laws, and the section on measuring shows how to collect your own:

  • vector and flat_set requested 524,288 bytes, 5.2 per element: the capacity doubled from 1 to 131,072 slots, which took 18 allocations. A reserve(100000) on the vector first would have made it one allocation of exactly 400,000 bytes; a flat_set has no reserve, but it can be built from a vector reserved that way.
  • deque also needs about 4 bytes per element, kept in blocks: libc++ uses blocks of 4,096 bytes and libstdc++ blocks of 512 bytes, which is why the two libraries made 106 and 790 allocations.
  • list requested 24 bytes per element in both libraries, and forward_list 16. A node holds the int and two pointers (list) or one (forward_list), padded to a multiple of 8 bytes, the alignment of a pointer.
  • set took 32 bytes per element with libc++ and 40 with libstdc++. A tree node holds three pointers (left child, right child and parent) and a colour flag beside the value; libc++ fits the one-byte flag and the int into the same 8 bytes, while libstdc++ gives the colour a padded 8-byte slot of its own.
  • unordered_set took about 30 bytes per element: a node per element plus an array of buckets of 8 bytes each. The libc++ node stores the element’s hash and takes 24 bytes; the libstdc++ node does not store the hash of an int and takes 16, but that library kept more buckets (172,933 against 102,877).

Step through one element of each node-based container, libc++ on the left and libstdc++ on the right, and add up what a single int costs in it:

Interactive · step by step The bytes of one int in each node Step through the nodes, one kind per row, libc++ on the left and libstdc++ on the right. Each sub-label adds up what one 4-byte int costs there.
The bytes of one int in each node, step 5 of 5. Showing vector, flat_set, forward_list node, libc++ list node, libstdc++ list node, libc++ set node, libstdc++ set node, libc++ hash node, libstdc++ hash node. In focus: libc++ hash node, libstdc++ hash node.vector, flat_set4 bytes, plus spare roomforward_list node16: a link, the int, padlibc++ list node24: 2 links, int, padlibstdc++ list node24: 2 links, int, padlibc++ set node32: 3 links, colour+intlibstdc++ set node40: colour, 3 links, intlibc++ hash node24: link, hash, int, padlibstdc++ hash node16: link, int, pad

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

Every step as text
  1. No node at all. A vector and a flat_set keep the ints themselves, 4 bytes each, in one buffer. They requested 5.2 bytes per int only because the capacity had doubled to 131,072 slots; reserve(100000) on the vector would have made it exactly 4.
  2. One link. A forward_list node holds a pointer to the next node, 8 bytes, and the 4-byte int, padded to 16 because a node starts at a multiple of 8, the alignment of a pointer. Both libraries requested 16 bytes per int.
  3. Two links. A list node adds a pointer to the previous node: 8 + 8 for the links, 4 for the int and 4 of padding make 24 bytes, six times the int itself, in both libraries.
  4. Three links and a colour. A tree node holds its left child, its right child and its parent, 24 bytes of links, and a colour flag. libc++ puts the one-byte flag and the int in the same 8 bytes, 32 in all; libstdc++ gives the colour an 8-byte slot of its own, 40 in all.
  5. Hash nodes. A hash node links to the next node. libc++ also stores the hash of its element, 24 bytes in all; libstdc++ does not store the hash of an int, 16 bytes. The bucket arrays come on top: about 32 and 30 bytes per int in all.

Each node-based container made one allocation per element, 100,000 in all (the unordered sets a few more, for their bucket arrays), against 18 for the vector. These are the bytes the containers asked for; the allocator rounds small requests up and keeps bookkeeping of its own, so the real memory used by the node-based containers is higher still.

Memory matters for speed as well as for size. A processor reads memory in fixed blocks called cache line: The block in which memory travels into the processor's caches, 128 bytes on this course's Mac. Reading one int brings in its whole line, so the ints next to it come almost free, while a read somewhere else waits for another line. More in “2D grids in C++: flat storage and std::mdspan”, 128 bytes on the processor used here, as the first line of the output shows. In a vector, the next element is usually in a line already read, and the processor fetches the following lines ahead of time when a loop walks forward. In a node container, the next element can be anywhere, so each step may wait for memory. The C++ Core Guidelines turn this into a rule of their own (Per.19): access memory predictably.

Key idea

A vector pays for its elements and its spare capacity; a node-based container pays an allocation and 16 to 40 bytes of node for every element, and its elements end up scattered in memory.

Checkpoint

Check: Memory per element

  1. Question 1 of 2 In this lesson's measurement, how many bytes did a std::forward_list<int> request per element, with both libraries?

    Type a number.

    A hint

    A forward_list node links only to the next node.

    Show the answer: Question 1 of 2

    Answer: 16 bytes

    A node holds one pointer to the next node, 8 bytes, and the 4-byte int, padded to 16 because nodes start at a multiple of 8, the alignment of a pointer. Both libraries requested 1,600,000 bytes for 100,000 ints.

  2. Question 2 of 2 Filling a vector with 100,000 ints took 18 allocations. How many would it take after calling reserve(100000) first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: One, of exactly 400,000 bytes

    Without reserve, the capacity doubled from 1 to 131,072 slots in 18 allocations. reserve(100000) allocates 100,000 slots of 4 bytes once, and the elements then fill them without another allocation.

A hash lookup stayed fastest from 1,000 to a million keys

Lookups by key are where the choice of container matters most often. This program stores n random 64-bit keys, each with a value, in four containers, and times lookups of keys that are present for n from 1,000 to 1,000,000:

  • a std::vector of pairs sorted by key, searched with std::ranges::lower_bound, a binary search;
  • std::map;
  • std::unordered_map;
  • std::flat_map.
lookups.cpp C++ · lookups.cpp
// Times lookups of keys that are present in four containers holding the same n key-value pairs, for n from 1,000 to
// 1,000,000. Each container answers the same 16,384 random queries; a round times each container once, and the
// table shows the fastest of 9 rounds, because other programs can only make a run slower, never faster.
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <flat_map>
#include <functional>
#include <map>
#include <print>
#include <random>
#include <unordered_map>
#include <utility>
#include <vector>

using Key = std::uint64_t;
using Clock = std::chrono::steady_clock;

int main() {
    std::mt19937_64 random(42);  // the engine's output is the same with every standard library
    const std::size_t queries_per_round = 16'384;
    const int rounds = 9;

    std::println("nanoseconds per lookup, fastest of {} rounds", rounds);
    std::println("{:>9} {:>14} {:>9} {:>19} {:>14}", "n", "sorted vector", "std::map", "std::unordered_map", "std::flat_map");
    for (std::size_t n : {1'000uz, 10'000uz, 100'000uz, 1'000'000uz}) {
        std::vector<std::pair<Key, Key>> items;  // random keys, each with its position as the value
        for (std::size_t i = 0; i < n; ++i) items.emplace_back(random(), i);
        std::vector<Key> queries;
        for (std::size_t i = 0; i < queries_per_round; ++i) queries.push_back(items[random() % n].first);

        auto sorted = items;
        std::ranges::sort(sorted);
        std::map<Key, Key> tree(items.begin(), items.end());
        std::unordered_map<Key, Key> hashed(items.begin(), items.end());
        std::flat_map<Key, Key> flat(items.begin(), items.end());

        // Each lookup adds the value it found, so the compiler cannot skip the work, and all four sums must agree.
        std::array<std::function<Key()>, 4> lookup_all{
            [&] { Key sum = 0; for (Key q : queries) sum += std::ranges::lower_bound(sorted, q, {}, &std::pair<Key, Key>::first)->second; return sum; },
            [&] { Key sum = 0; for (Key q : queries) sum += tree.find(q)->second; return sum; },
            [&] { Key sum = 0; for (Key q : queries) sum += hashed.find(q)->second; return sum; },
            [&] { Key sum = 0; for (Key q : queries) sum += flat.find(q)->second; return sum; },
        };
        std::array<double, 4> fastest;
        fastest.fill(1e300);
        std::array<Key, 4> sums{};
        for (int round = 0; round < rounds; ++round) {
            for (std::size_t c = 0; c < lookup_all.size(); ++c) {
                auto start = Clock::now();
                sums[c] = lookup_all[c]();
                std::chrono::duration<double, std::nano> took = Clock::now() - start;
                fastest[c] = std::min(fastest[c], took.count() / queries_per_round);
            }
        }
        bool agree = std::ranges::all_of(sums, [&](Key s) { return s == sums[0]; });
        std::println("{:>9} {:>14.1f} {:>9.1f} {:>19.1f} {:>14.1f}   same answers: {}", n, fastest[0], fastest[1], fastest[2], fastest[3], agree);
    }
}
Nanoseconds per lookup with Apple clang and with GCC Python · lookups_session.py
from session import run

# lookups.cpp built with optimisation (-O2), as timings only mean something for optimised code, and run once with
# each compiler and its standard library. The first command names the processor the times come from.
run("""
/usr/sbin/sysctl -n machdep.cpu.brand_string
clang++ -std=c++23 -O2 -Wall -Wextra lookups.cpp -o lookups
./lookups
g++-16 -std=c++23 -O2 -Wall -Wextra lookups.cpp -o lookups-gcc
./lookups-gcc
""")

Output

$ /usr/sbin/sysctl -n machdep.cpu.brand_string
Apple M5 Pro
$ clang++ -std=c++23 -O2 -Wall -Wextra lookups.cpp -o lookups
$ ./lookups
nanoseconds per lookup, fastest of 9 rounds
        n  sorted vector  std::map  std::unordered_map  std::flat_map
     1000           20.7      44.8                 6.1           21.6   same answers: true
    10000           48.7      98.1                11.0           45.3   same answers: true
   100000          105.1     312.7                24.6           97.1   same answers: true
  1000000          388.6    2088.0                34.3          362.1   same answers: true
$ g++-16 -std=c++23 -O2 -Wall -Wextra lookups.cpp -o lookups-gcc
$ ./lookups-gcc
nanoseconds per lookup, fastest of 9 rounds
        n  sorted vector  std::map  std::unordered_map  std::flat_map
     1000           55.3      44.4                 7.1           50.3   same answers: true
    10000           84.1     115.4                13.4           74.2   same answers: true
   100000          193.1     395.4                21.6          112.4   same answers: true
  1000000          256.7     990.0                32.3          214.4   same answers: true

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 lookups_session.py

The numbers change from run to run, but in every run on this machine the pattern was the same:

  • std::unordered_map was the fastest at every size, with both compilers: a few nanoseconds per lookup at 1,000 elements and a few dozen at a million. A lookup computes one hash and usually reads one bucket and one node, however large the map grows.
  • std::map was the slowest from 10,000 elements up. A lookup walks from the root through about 10 levels at 1,000 elements and 20 at a million, and once the tree no longer fits in the caches, most of those steps wait for memory.
  • The sorted vector and std::flat_map stayed close to each other: both are binary searches over contiguous memory. At a million elements flat_map was usually ahead, because its search reads only the 8-byte keys, which sit in a vector of their own, while the sorted vector’s search reads 16-byte pairs.
  • At 1,000 elements, GCC’s binary searches were slower than its std::map, while Clang’s were about twice as fast as its own. The next section shows why.

Times at a million elements vary most from one run to the next, because they depend on how much of the processor’s caches the other programs running at the same moment occupy.

Checkpoint

Check: Lookup speed as the size grows

  1. One question In the lookup timings at 1,000,000 elements, which container was the slowest with both compilers?

    Choose one answer.

    Show the answer: One question

    Answer: std::map

    From 10,000 elements up, std::map was the slowest in every recorded run. Its O(log n) is the same as a binary search's, but each of its steps is a node somewhere on the heap.

The same source ranked differently with two compilers

The C++ source was the same for both compilers, so the difference at 1,000 elements comes from the machine code. This file holds only the sorted vector’s lookup, and the session keeps the instructions that decide, at each step of the binary search, which half the search continues in:

lower_bound_value.cpp C++ · lower_bound_value.cpp
// The lookup that lookups.cpp times in the sorted vector, as a function on its own, so that its machine code is easy
// to read: a binary search for the first pair whose key is not less than q.
#include <algorithm>
#include <cstdint>
#include <utility>
#include <vector>

using Key = std::uint64_t;

Key value_of(const std::vector<std::pair<Key, Key>>& sorted, Key q) {
    return std::ranges::lower_bound(sorted, q, {}, &std::pair<Key, Key>::first)->second;
}
The deciding instructions in each compiler's output Python · codegen_session.py
from session import run

# lower_bound_value.cpp compiled to assembly (-S) by each compiler with -O2. grep keeps the instructions that decide
# which half the search continues in: csel is a conditional select, and b.lo, b.hs, bcc and bcs are conditional
# branches (Clang and GCC spell the same branch two ways).
run("""
clang++ -std=c++23 -O2 -S lower_bound_value.cpp -o clang.s
grep -E "csel|b[.]lo|b[.]hs|bcc|bcs" clang.s
g++-16 -std=c++23 -O2 -S lower_bound_value.cpp -o gcc.s
grep -E "csel|b[.]lo|b[.]hs|bcc|bcs" gcc.s
""")

Output

$ clang++ -std=c++23 -O2 -S lower_bound_value.cpp -o clang.s
$ grep -E "csel|b[.]lo|b[.]hs|bcc|bcs" clang.s
	csel	x9, x9, x10, lo
	csel	x8, x11, x8, lo
$ g++-16 -std=c++23 -O2 -S lower_bound_value.cpp -o gcc.s
$ grep -E "csel|b[.]lo|b[.]hs|bcc|bcs" gcc.s
	bcc	L8

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

Clang turned the decision into two csel instructions, conditional selects, which pick one of two values without jumping anywhere. GCC turned it into bcc, a conditional branch. A processor guesses which way each branch goes before it knows, so that it can keep working; this branch prediction: The processor's guess of which way a conditional branch will go, made before the comparison is finished so that it can keep working. A wrong guess throws that work away; with random queries, a binary search's branch is guessed wrong about half the time. guesses wrong about half the time with random queries, and every wrong guess throws work away. A thousand elements fit easily in the caches, so those wrong guesses dominate the cost. Big-O notation says nothing about this, and the same container gave a different ranking with each compiler.

Checkpoint

Check: Branches and conditional selects

  1. One question What does the csel instruction that Clang emitted for the binary search do?

    Choose one answer.

    Show the answer: One question

    Answer: It picks one of two values according to a condition, without jumping

    At each step the search decides which half to continue in. Clang compiled the decision into conditional selects, which pick a value; GCC into a conditional branch, which the processor guesses and, with random queries, often guesses wrong.

A vector beat a list at inserting in sorted order

A common argument for std::list is its constant-time insertion in the middle. This program keeps n random numbers in sorted order by inserting each one at its place, once in a vector and once in a list. Each container first walks from the front to the place:

sorted_insert.cpp C++ · sorted_insert.cpp
// Keeps n random numbers in sorted order by inserting each one where it belongs, once in a std::vector and once in a
// std::list. Both must first walk to the right position; then the vector shifts the later elements up by one, while
// the list only links in a new node. Times are the fastest of 3 runs.
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <list>
#include <print>
#include <random>
#include <vector>

using Clock = std::chrono::steady_clock;

template <class Container>
double fastest_ms(const std::vector<int>& values, long long& check) {
    double best = 1e300;
    for (int run = 0; run < 3; ++run) {
        auto start = Clock::now();
        Container c;
        for (int v : values) {
            auto pos = std::find_if(c.begin(), c.end(), [v](int x) { return x >= v; });  // walk to the position
            c.insert(pos, v);
        }
        std::chrono::duration<double, std::milli> took = Clock::now() - start;
        best = std::min(best, took.count());
        check = c.front() + c.back();
    }
    return best;
}

int main() {
    std::mt19937 random(7);
    std::println("{:>7} {:>12} {:>12}", "n", "vector ms", "list ms");
    for (int n : {1'000, 3'000, 10'000}) {
        std::vector<int> values;
        for (int i = 0; i < n; ++i) values.push_back(int(random() % 1'000'000));
        long long a = 0, b = 0;
        double v = fastest_ms<std::vector<int>>(values, a);
        double l = fastest_ms<std::list<int>>(values, b);
        std::println("{:>7} {:>12.2f} {:>12.2f}   same result: {}", n, v, l, a == b);
    }
}
Milliseconds to insert n numbers in sorted order Python · sorted_insert_session.py
from session import run

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

Output

$ clang++ -std=c++23 -O2 -Wall -Wextra sorted_insert.cpp -o sorted_insert
$ ./sorted_insert
      n    vector ms      list ms
   1000         0.11         0.35   same result: true
   3000         0.80         5.59   same result: true
  10000         8.47       499.49   same result: true
$ g++-16 -std=c++23 -O2 -Wall -Wextra sorted_insert.cpp -o sorted_insert-gcc
$ ./sorted_insert-gcc
      n    vector ms      list ms
   1000         0.11         0.38   same result: true
   3000         0.88         6.45   same result: true
  10000        10.14       581.24   same result: true

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 sorted_insert_session.py

The vector won at every size with both compilers: about three times as fast at 1,000 numbers, and more than five times as fast at 3,000 and 10,000. Both containers spend most of the time walking to the place, and that walk is linear for both. The vector walks through neighbouring memory, while the list follows a pointer from node to node, and the nodes of a list kept in sorted order lie scattered in memory. The vector then shifts the later elements with one block move, which processors do quickly. A sorted vector could even find the place by binary search, O(log n), which a list cannot do because it has no random access.

The list’s constant-time insertion pays off when the program already holds an iterator to the place, for example one it kept from an earlier search, or when it moves whole runs of nodes from one list to another with splice, which never copies an element. The next lesson covers both.

Choosing a list for fast insertion in the middle

“A list inserts in O(1)” is true only for a program that already holds an iterator to the place. A program that searches for the place first pays a linear walk through scattered nodes, which made the list slower than a vector at every size above. Hold iterators, or splice runs of nodes, before you reach for std::list.

Checkpoint

Check: Sorted insertion in a vector or a list

  1. One question When does the constant-time insertion of std::list actually pay off?

    Choose one answer.

    Show the answer: One question

    Answer: When the program already holds an iterator to the place, or moves runs of nodes with splice

    A list inserts in constant time only once you hold an iterator to the place. To keep it sorted, the program first walks to the place, and in the measurement that walk made the list slower than the vector at every size.

Five rules make a measurement worth trusting

The measurements above follow five rules, and so should yours:

  1. Measure an optimised build, with the flags you ship. The examples use -O2; a build without optimisation mostly measures debugging code.
  2. Use your real key and value types and your real sizes. Strings compare and hash at a very different speed from integers, and a container that fits in the caches behaves differently from one that does not.
  3. Use the results. Each example adds up the values it found and checks that all containers agree; if the results were thrown away, the optimiser could delete the very work being timed.
  4. Repeat, and keep the fastest run or look at the spread of many. Other programs only ever add time to a run.
  5. Write down the machine and the compiler. The tables here come from one laptop processor, and the ranking changed when only the compiler changed.

Follow one measurement through the five rules, with what this lesson’s programs did at each:

Interactive · stage by stage A measurement you can trust, step by step Step through the five rules in the order a measurement meets them. Each stage says what this lesson's programs did to keep the rule.
A measurement you can trust, step by step, step 6 of 6. Showing Build as you ship, Use your types and sizes, Use every result, Repeat, keep the fastest, Record where it ran. In focus: again, Build as you ship.a new compiler or flagBuild as you shipthe examples use -O2Use your types and sizes1,000 to 1,000,000 keysUse every resultsums checked: same answersRepeat, keep the fastestfastest of 9 roundsRecord where it ranthe processor, both compilers

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

Every step as text
  1. An optimised build. Build the way you ship. Every example in this lesson is compiled with -O2; a build without optimisation mostly measures debugging code, and its ranking can differ from the real one.
  2. Real data. Use your own key and value types and your own sizes. The lookups ran at four sizes, from 1,000 keys, which fit in the caches, to 1,000,000, which do not, and the ranking changed between them.
  3. Results that are used. Add up what each container found and check that they all agree, as the examples print with "same answers: true". If a result is thrown away, the optimiser may delete the very work being timed.
  4. Several runs. Other programs only ever add time to a run, so repeat it and keep the fastest, or look at the spread of many runs. lookups.cpp keeps the fastest of 9 rounds and sorted_insert.cpp the fastest of 3.
  5. A record of where it ran. Name the processor and both compilers, as the sessions do with sysctl and the two compile commands. The same source ranked the containers differently with GCC and with Clang.
  6. Measure again after a change. A new compiler, a new flag or a new data size is a new measurement: go back to the first rule. Without one, the C++ Core Guidelines say it in a line (Per.6): make no claims about performance without measurements.

The examples time with a few lines of std::chrono, which is enough to see differences of this size. For smaller differences, a benchmarking library such as nanobench, a single header file, handles warm-up, repetitions and the optimiser, and reports how much the runs vary. The C++ Core Guidelines (Per.6) say it in one line: don’t make claims about performance without measurements.

Key idea

A benchmark is evidence only when it times an optimised build on your own types and sizes, uses every result, keeps the fastest of several runs and names the machine and the compiler.

Checkpoint

Check: Measuring a container fairly

  1. Question 1 of 2 Why does each timing example add up the values it found and check that the containers agree?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: So that the optimiser cannot delete the work being timed, and a wrong result shows at once

    If the results of the timed lookups were thrown away, an optimising compiler could remove the lookups, and the benchmark would time nothing. Adding them up and comparing the totals keeps the work, and proves that all the containers found the same values.

  2. Question 2 of 2 Five of a benchmark's rounds took 410, 395, 402, 980 and 399 nanoseconds per lookup. Following this lesson's rule, which number describes the container?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 395, the fastest round

    Repeat the measurement and keep the fastest run, or look at the spread of many runs. Disturbances only ever add time, which is why one round at 980 ns says more about the machine than about the container.

Four questions pick the container to start with

For a first choice, ask four questions in order. The first answer “yes” names the container to start with:

Four questions in order lead to std::map or std::set, std::unordered_map, std::deque or std::list; otherwise std::vector.1. Do you need the keys in order,or the nearest key to a value? yes: std::map or std::set(std::flat_map or std::flat_setwhen built once, then mostly read)2. Do you look values upby key, in any order? yes: std::unordered_mapor std::unordered_set3. Do you add or removeat the front as well as the back? yes: std::deque4. Must iterators survive insertionsand erasures in the middle,or do you move runs between lists? yes: std::liststd::vector(std::array when the sizeis fixed at compile time) then measurenononono

Four questions that pick a container to start with

Text description of the diagram

The diagram is a column of four questions, asked from top to bottom. Each box names the container to start with when the answer is yes; an arrow labelled "no" leads to the next question.

  1. Do you need the keys in order, or the nearest key to a value? Yes: std::map or std::set, or std::flat_map or std::flat_set when the data is built once and then mostly read.
  2. Do you look values up by key, in any order? Yes: std::unordered_map or std::unordered_set.
  3. Do you add or remove elements at the front as well as at the back? Yes: std::deque.
  4. Must iterators survive insertions and erasures in the middle, or do you move runs of elements between lists? Yes: std::list.
  5. If every answer is no, the last box says std::vector, or std::array when the size is fixed at compile time, and then measure.

The diagram gives the first answer; your own program usually has more than one need at once. Answer the questions in the table below about a program of yours, and it marks the containers that fit, the ones that fit with a caveat, and the reason each of the others is ruled out, with this lesson’s numbers in every cell:

Interactive · answer and compare Which container fits your program? Answer the questions about what your program does. The table marks the containers that fit, and says why the others do not.
Do you need the keys in order, or the nearest key to a value?
Do you look values up by a key?
Do you add or remove at the front as well as at the back?
Must references or iterators stay valid while other elements are added or removed?
Is the data built once, and then mostly read?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Seven containers against the five things that decide between them (numbers from this lesson's runs)
Container A pass over every element Inserting and erasing Finding by key Keys in order References that survive
std::vector Keeps its elements in: one block, growing at the end Good contiguous: the fastest loop of all Mixed O(1) amortised at the end, O(n) anywhere else; no push_front Mixed a scan, or about 20 probes for a million values kept sorted Mixed only if you keep it sorted yourself Poor growth moves every element, and old pointers dangle
std::array Keeps its elements in: one block, its size fixed when compiled Good contiguous, with no allocation at all Poor the size is fixed: nothing is added or removed Mixed a scan, or a binary search if sorted Mixed only if you sort it yourself Good nothing is inserted, so no element moves
std::deque Keeps its elements in: fixed-size blocks, growing at both ends Mixed blocks of a fixed size: each index finds its block first Mixed O(1) at both ends, O(n) in the middle Mixed a scan, or a binary search if kept sorted Mixed only if you keep it sorted yourself Mixed references survive growth at the ends; iterators do not
std::list Keeps its elements in: a node per element Poor a 24-byte node per int, scattered in memory Good O(1) once you hold an iterator to the place Poor a walk from one end, O(n) Mixed sorted inserts walk to each place: slower than a vector here Good nodes never move; only erased elements are lost
std::map or std::set Keeps its elements in: a balanced tree, sorted by key Poor a tree node per element: 32 or 40 bytes per int Good O(log n), and no other element moves Mixed O(log n): the slowest lookups here from 10,000 keys up Good always in key order, with lower_bound and ranges Good nodes never move; only erased elements are lost
std::flat_map or flat_set Keeps its elements in: sorted vectors Good the keys and the values are vectors Poor O(n): every later key and value moves Good O(log n) over contiguous keys, close to a sorted vector Good always in key order, with lower_bound Poor an insertion or erasure may move every element
std::unordered_map or set Keeps its elements in: buckets of chained nodes Poor a node per element: about 30 bytes per int with the buckets Good O(1) on average Good O(1) on average: the fastest lookups at every size here Poor an unspecified order, and no lower_bound Mixed references survive; iterators do not after a rehash
How the answers decide
  • “Do you need the keys in order, or the nearest key to a value?” Yes: rules out std::unordered_map or set. Its elements come out in an unspecified order and it has no lower_bound, so a report in key order needs a sort first.
  • “Do you need the keys in order, or the nearest key to a value?” Yes: rules out std::list. A list cannot binary-search: finding the nearest key in a sorted list walks from one end.
  • “Do you need the keys in order, or the nearest key to a value?” Yes: adds a caveat to std::vector, std::array and std::deque. A sequence keeps keys in order only if you keep it sorted yourself, and every insertion into the middle moves elements.
  • “Do you look values up by a key?” Yes: rules out std::list. Finding a key in a list walks from one end, O(n), following one pointer per step.
  • “Do you look values up by a key?” Yes and “Do you need the keys in order, or the nearest key to a value?” No: adds a caveat to std::map or std::set. It works, but its walk through scattered tree nodes gave the slowest lookups here from 10,000 keys up.
  • “Do you look values up by a key?” Yes and “Do you need the keys in order, or the nearest key to a value?” No: adds a caveat to std::vector, std::array, std::deque and std::flat_map or flat_set. Binary search over sorted keys works, but a hash lookup was faster at every size in this lesson's timings.
  • “Do you look values up by a key?” No and “Do you need the keys in order, or the nearest key to a value?” No: rules out std::map or std::set, std::flat_map or flat_set and std::unordered_map or set. Without lookups by key or keys in order, a container built around keys only adds nodes, hashing or sorting.
  • “Do you add or remove at the front as well as at the back?” Yes: rules out std::vector and std::array. A vector has no push_front, because adding at the front moves every element; an array cannot grow at all.
  • “Do you add or remove at the front as well as at the back?” No and “Must references or iterators stay valid while other elements are added or removed?” No: adds a caveat to std::deque and std::list. Without work at the front or handles to keep, a vector does the same job in one block, which is faster to loop over.
  • “Must references or iterators stay valid while other elements are added or removed?” Yes: rules out std::vector and std::flat_map or flat_set. A vector that grows, or any insertion into a flat container, can move every element, so old pointers and references dangle.
  • “Must references or iterators stay valid while other elements are added or removed?” Yes: adds a caveat to std::deque. References survive growth at both ends, but every iterator is invalidated, and an insertion in the middle invalidates everything.
  • “Must references or iterators stay valid while other elements are added or removed?” Yes: adds a caveat to std::unordered_map or set. References and pointers survive every insertion, but a rehash invalidates all iterators.
  • “Is the data built once, and then mostly read?” Yes, built once and “Do you need the keys in order, or the nearest key to a value?” Yes: adds a caveat to std::map or std::set. For data built once and then read, a flat container does the same ordered lookups over contiguous keys, without a node per element.
  • “Is the data built once, and then mostly read?” No, it changes all the time: adds a caveat to std::flat_map or flat_set. Every insertion or erasure in a flat container is O(n), because the later keys and values move to make room.

In short: a vector unless something rules it out; a deque for work at both ends; a list only for iterators that must survive or for splicing; a map for keys in order and a flat map for keys in order that rarely change; an unordered map for lookups by key alone. Then measure, as the previous section did.

Practise: eight programs, eight containers

Each of the eight questions below describes a program. Choose the container you would start with, and compare your reasons with the explanation that appears once you answer. More than one container can work for some of them; the explanations say what each alternative would cost.

Checkpoint

Programs 1 to 3

  1. Question 1 of 3 A game updates all of its 300 enemies 60 times a second. Enemies appear and disappear a few times a second, and their order does not matter. Which container would you start with?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: std::vector

    Updating every enemy in every frame is a loop over the whole collection, which a vector does fastest. Because the order does not matter, removing an enemy needs no shifting: move the last element into its place and call pop_back, which takes constant time. A list or a set would make every frame's loop follow pointers between nodes.

  2. Question 2 of 3 A print server handles jobs in the order they arrive. New jobs join at the back, and the printer takes the oldest job from the front.

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: std::deque

    Adding at one end and removing at the other, both in constant time, is what a deque is for, and std::queue, a container adaptor, uses a deque by default. A vector would move every remaining job each time it removes the first one.

  3. Question 3 of 3 A spell checker loads 300,000 dictionary words once, then checks every word of a document against them. It never lists the dictionary.

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: std::unordered_set<std::string>

    Only membership matters, so a hash set answers each check in constant time on average. A std::flat_set, built once from the sorted words, would also do well with its binary searches over contiguous memory. std::set needs a node per word, and its tree is the structure that gave the slowest lookups in this lesson's timings, as std::map; std::find on an unsorted vector reads the whole dictionary for every word that is missing.

Checkpoint

Programs 4 to 6

  1. Question 1 of 3 A leaderboard must show the ten highest scores after every new score, and answer questions such as "which players scored between 500 and 600?". Several players can have the same score.

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: A std::multimap from score to player

    Keys in order and questions about ranges point to an ordered container, and equal scores need the multi version (a std::set of score and player pairs works too). The ten highest are the last ten elements, and lower_bound(500) and upper_bound(600) mark the players in the range, each in O(log n). A hash map has no order, and sorting a vector after every score costs O(n log n) each time.

  2. Question 2 of 3 A program loads 250 country codes with their names at start-up, then looks codes up millions of times and prints the countries in alphabetical order in a report.

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: std::flat_map<std::string, std::string>

    Built once, then only read, and needed in order: the case flat_map was made for. Lookups are binary searches over contiguous keys, and its O(n) insertion never matters because nothing is inserted after loading. A std::map would be correct too, with a node per entry; an unordered_map would need a separate sort for the report.

  3. Question 3 of 3 A music player lets the user move a block of 50 songs from one play queue to another, and keeps an iterator to the song now playing, which must stay valid while songs are added and removed elsewhere in the queue.

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: std::list

    list::splice moves a run of nodes from one list to another without copying a single song, and a list iterator stays valid until its own element is erased. In a vector, an insertion or erasure before the current song would shift it and invalidate the iterator, and a deque invalidates every iterator whenever it inserts anywhere.

Checkpoint

Programs 7 and 8

  1. Question 1 of 2 A report keeps the twelve monthly totals of a year, and the number of months never changes.

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::array<double, 12>

    A size known when the program is compiled needs no heap allocation: std::array keeps its twelve values inside the object itself and indexes them like a vector. A vector would work, with one allocation and room to grow that the report never uses.

  2. Question 2 of 2 A recorder appends sensor samples at the end, and other parts of the program keep pointers to individual samples for as long as the recording runs.

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: std::deque

    Adding at either end of a deque invalidates its iterators but never the pointers and references to its elements, because the elements themselves never move. A vector moves all of its elements when it grows, which leaves the old pointers dangling, and a flat_set shifts elements on every insertion. Storing indexes into a vector instead of pointers is the other good answer.

Then test the eight ideas of the lesson, from container families to fair benchmarks, in an order that follows your answers: a missed idea comes back, and every option carries its reason:

Practice that adapts to you

Practise this lesson

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

  1. Question 1 of 18 Which containers keep their elements sorted by key, one node per element, in a balanced tree?

    Choose one answer.

    Show the answer: Question 1 of 18

    Answer: set, map, multiset and multimap

    The ordered associative containers keep their elements sorted by key in a balanced tree, one node per element. The standard specifies only their costs and invalidation rules, which a balanced tree such as a red-black tree meets.

  2. Question 2 of 18 What does a std::priority_queue<int> keep its elements in when you do not name another container?

    Choose one answer.

    Show the answer: Question 2 of 18

    Answer: A std::vector<int>

    The container adaptors, stack, queue and priority_queue, keep their elements in another container: a deque by default for stack and queue, and a vector for priority_queue.

  3. Question 3 of 18 Which of these lookups does the standard guarantee only on average, with a linear worst case?

    Choose one answer.

    Show the answer: Question 3 of 18

    Answer: std::unordered_map::find

    A hash lookup is constant time on average, but when many keys land in the same bucket it compares the key with each of them, so the worst case is linear in the size. The other three are logarithmic in every case: a balanced tree walk or a binary search.

  4. Question 4 of 18 Which of these can find the first key that is not less than a given value in O(log n)?

    Choose every answer that is right.

    Show the answer: Question 4 of 18

    Answer:

    • std::flat_map::lower_bound
    • std::ranges::lower_bound on a sorted std::vector
    • std::map::lower_bound

    Ordered containers and sorted vectors answer "the nearest key at or above k" with lower_bound in O(log n). An unordered_map has no such function, because its order is unspecified.

  5. Question 5 of 18 A std::list<int> holds n elements. You have the value 42, not an iterator, and must insert 7 just after the first 42. What does that cost?

    Choose one answer.

    Show the answer: Question 5 of 18

    Answer: O(n) to walk to the 42, then O(1) to link the new node

    A list inserts in constant time only once you hold an iterator to the place. Finding the first 42 is a linear walk, so the whole operation is O(n), even though no element moves.

  6. Question 6 of 18 In this lesson's measurement, how many bytes did a std::list<int> request per element, with both standard libraries?

    Type a number.

    Show the answer: Question 6 of 18

    Answer: 24 bytes

    Each node holds a pointer to the next node, a pointer to the previous one and the 4-byte int, padded to a multiple of 8 bytes: 8 + 8 + 8 = 24, six times the size of the int itself, in a separate allocation per element.

  7. Question 7 of 18 Why did a std::set<int> request 32 bytes per element with libc++ and 40 with libstdc++?

    Choose one answer.

    Show the answer: Question 7 of 18

    Answer: libc++ fits the one-byte colour flag and the int into the same 8 bytes; libstdc++ gives the colour a padded 8-byte slot of its own

    A tree node holds its left child, right child and parent, 24 bytes of pointers, plus a colour flag and the int. libc++ packs the flag and the int into one 8-byte slot, 32 bytes in all; libstdc++ pads the flag to 8 bytes before the pointers, 40 in all.

  8. Question 8 of 18 Using this lesson's measurement, how many megabytes would a std::list<int> of 1,000,000 elements request, with either library? (1 MB = 1,000,000 bytes.)

    Type a number.

    Show the answer: Question 8 of 18

    Answer: 24 MB

    Each element costs a 24-byte node, so a million elements request 24,000,000 bytes, 24 MB, in a million separate allocations, against 4 MB for the ints themselves. The allocator's own bookkeeping comes on top.

  9. Question 9 of 18 Which container answered lookups the fastest at every size, from 1,000 to 1,000,000 elements, with both compilers?

    Choose one answer.

    Show the answer: Question 9 of 18

    Answer: std::unordered_map

    std::unordered_map took a few nanoseconds per lookup at 1,000 elements and a few dozen at a million, in every recorded run, with both compilers.

  10. Question 10 of 18 At a million elements, std::flat_map was usually ahead of the sorted vector of key-value pairs. Why?

    Choose one answer.

    Show the answer: Question 10 of 18

    Answer: Its search reads only the 8-byte keys, which sit in a vector of their own

    Both are binary searches over contiguous memory, about 20 probes for a million elements. A flat_map keeps its keys apart from its values, so its probes read half as many bytes as probes into a vector of pairs.

  11. Question 11 of 18 Why does a conditional branch slow a binary search down when the queries are random?

    Choose one answer.

    Show the answer: Question 11 of 18

    Answer: The processor guesses each branch before it knows the answer, and with random queries it guesses wrong about half the time, throwing work away

    A processor guesses which way a branch goes so that it can keep working. Random queries make each decision of a binary search a coin toss, and every wrong guess costs the work done on the wrong path. At 1,000 elements, which fit in the caches, those guesses dominated.

  12. Question 12 of 18 A colleague benchmarks with GCC only and concludes that std::map beats a sorted vector at 1,000 elements. What does this lesson's run suggest?

    Choose one answer.

    Show the answer: Question 12 of 18

    Answer: Measure with the compiler you ship; Clang compiled the same search with conditional selects and ranked the two the other way

    The same C++ source ranked the containers differently with two compilers, because one compiled the decision of the binary search into a branch and the other into conditional selects. A ranking is a fact about a compiler, a library and a machine, so measure with yours.

  13. Question 13 of 18 When the program kept n numbers sorted by inserting each one at its place, what took most of the time in both containers?

    Choose one answer.

    Show the answer: Question 13 of 18

    Answer: Walking from the front to the place, which is linear in both

    Both containers first walk to the place, which is linear. The vector walks through neighbouring memory and then shifts the rest with one block move; the list follows pointers to nodes scattered in memory, and that is slower at every size measured.

  14. Question 14 of 18 How could the sorted vector find the place for each new number faster than by walking, in a way a list cannot?

    Choose one answer.

    Show the answer: Question 14 of 18

    Answer: With a binary search such as std::ranges::lower_bound, in O(log n), because a vector has random access

    A sorted vector can find each place by binary search in O(log n). A list cannot, because it has no random access, so its only way to the place is a linear walk.

  15. Question 15 of 18 Why should a container benchmark use an optimised build, such as one compiled with -O2?

    Choose one answer.

    Show the answer: Question 15 of 18

    Answer: Because a build without optimisation mostly measures debugging code, not the containers

    Measure an optimised build with the flags you ship. Without optimisation the timing is dominated by code that the release build removes, and its ranking can differ.

  16. Question 16 of 18 Your program's keys are 40-character strings, but your benchmark of the candidate containers uses ints. Which rule does it break?

    Choose one answer.

    Show the answer: Question 16 of 18

    Answer: Use your real key and value types; strings compare and hash at a very different speed from integers

    A benchmark should use the program's real key and value types and real sizes. Integers compare in one instruction; 40-character strings compare and hash byte by byte, and may not fit in the caches the same way.

  17. Question 17 of 18 Which container does this lesson tell you to start with, unless an operation or a guarantee gives you a reason to choose another?

    Choose one answer.

    Show the answer: Question 17 of 18

    Answer: std::vector

    Start with std::vector, as the C++ Core Guidelines advise (SL.con.2), and choose another container for a reason: work at the front, lookups by key, keys in order, or references that must survive insertions.

  18. Question 18 of 18 A program appends events at the end of a log, and a viewer shows the newest 100 first. Nothing is looked up by key or removed. Which container would you start with?

    Choose one answer.

    Show the answer: Question 18 of 18

    Answer: std::vector, read from its end

    Appending at the end and reading in order, forwards or backwards, is a vector's job. Every question of the decision answers no, so the last box applies: std::vector, then measure.

Interview questions

Fresher · Why does std::vector have no push_front, while std::deque and std::list do?

The standard offers push_front only on sequence containers that can do it in amortised constant time, and a vector cannot: its elements sit in one block of memory, so adding at the front means moving every element one place up, which is linear in the size. A deque keeps its elements in fixed-size blocks and can add a block in front, and a list just links in a new node, so both add at the front in constant time. A vector can still insert at the front with v.insert(v.begin(), x), which is fine for small vectors or rare insertions. A program that adds at the front often should use a deque, or build the sequence in reverse and call std::ranges::reverse once at the end.

An interviewer usually follows this answer with the cost of one front insertion and the way round it. Decide both:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: a std::vector<int> holds 1,000,000 elements and has spare capacity. How many elements does v.insert(v.begin(), x) move to make room?

    Type a number.

    A hint

    Every element is one place too far to the left.

    Show the answer: Question 1 of 2

    Answer: 1000000 elements

    With spare capacity there is no reallocation, but every one of the 1,000,000 elements moves one place up before x goes into position 0. That is why insertion at the front of a vector is linear, and why it has no push_front.

  2. Question 2 of 2 Follow-up: a program adds elements only at the front while it builds a sequence, then only reads it from first to last. How can it keep a std::vector and stay fast?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: push_back each element, then call std::ranges::reverse once at the end

    Building the sequence in reverse with push_back and reversing it once costs O(n) in all. Inserting each element at the front would move every element already stored, O(n²) for the whole build.

The module’s bank holds two harder interview questions built on this lesson’s measurements. One profiles a session store whose map lookups take most of the time; the other fits 50 million pairs into a memory budget:

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

  1. Mid to senior

    A service keeps 2 million sessions in a std::map<std::uint64_t, Session> keyed by random 64-bit ids, and profiles show map::find taking most of the time. Which containers would you consider instead, how would you show that a change is worth it, and what could make it a mistake?

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

  2. Mid to senior

    You must keep 50 million (user id, score) pairs in memory, with 64-bit ids and 32-bit scores, under a 2 GB limit, and answer lookups of a score by id. Estimate what std::map, std::unordered_map and a sorted std::vector of pairs would need, and pick one.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Start with std::vector, and choose another container for a reason: work at the front, lookups by key, keys in order, or references that must survive insertions.
  • The standard specifies the cost of every operation, not the data structure: map is O(log n), unordered_map is O(1) on average and O(n) at worst, and flat_map finds in O(log n) but inserts in O(n).
  • Node-based containers allocate once per element and need several times the memory of the elements themselves: 24 bytes per int in a list, 32 or 40 in a set, depending on the library.
  • In the lookup timings, unordered_map was the fastest at every size and std::map the slowest from 10,000 elements up; the sorted vector and flat_map were close to each other.
  • The same source code ranked differently with GCC and Clang, because one compiled a decision into a branch and the other into a conditional select. Measure with your compiler, your data and your sizes.

Terms in this lesson

branch prediction
The processor's guess of which way a conditional branch will go, made before the comparison is finished so that it can keep working. A wrong guess throws that work away; with random queries, a binary search's branch is guessed wrong about half the time.
container adaptor
A class template that keeps its elements in another container and offers a narrower or different interface: std::stack and std::queue on a std::deque by default, std::priority_queue on a std::vector, and the C++23 flat containers on sorted vectors.
ordered associative container
std::set, std::map, std::multiset or std::multimap: a container that keeps its elements sorted by key, one node per element, in a balanced tree, so that finding, inserting and erasing a key take O(log n).
red-black tree
A binary search tree that marks each node red or black and recolours and rotates nodes on every insertion and erasure to stay balanced, so that a lookup visits O(log n) nodes. libc++ and libstdc++ build std::map and std::set as red-black trees.
sequence container
A container that keeps its elements in the order they were put in: std::array and std::vector in one block, std::deque in fixed-size blocks, std::list and std::forward_list in one node per element.
unordered associative container
std::unordered_set, std::unordered_map or one of their multi versions: a hash table that picks a bucket for each element from a hash of its key, so that lookups take constant time on average, and lists its elements in an unspecified order.

Corrections

  • The memory section now says that the unordered sets made a few more allocations than one per element, and that reserve is a member of the vector, not of flat_set.

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.