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.
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
What you’ll learn · Before you start
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
On this page
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,listandforward_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,multisetandmultimap, 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_multisetandunordered_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,queueandpriority_queue, and since C++23flat_set,flat_map,flat_multisetandflat_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:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
multiversions 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::mapas 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. andstd::unordered_mapas 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. Aflat_mapuses one vector for the keys and another for the values. std::spanandstd::string_viewlook like containers but are views: they refer to elements that something else owns.
Checkpoint
Check: The four families of containers
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
vectorand adeque; O(i) in alist, which has to walk from one end. - Add or remove at the back: O(1) amortised in a
vector; O(1) in adequeand alist. - Add or remove at the front: O(n) in a
vector; O(1) in adequeand alist. - Insert or erase in the middle: O(n) in a
vector, whose later elements move, and in adeque, whose nearer end moves; O(1) in alist, 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
vectorordequeis sorted.
For the containers that look up by key:
- Find a key: O(log n) in a
maporsetand in aflat_maporflat_set; O(1) on average and O(n) at worst in anunordered_maporunordered_set. - Insert a key: O(log n) in a
map; O(1) on average and O(n) at worst in anunordered_map; O(n) in aflat_map, whose later elements move. - Erase at an iterator: O(1) amortised in a
map; O(1) on average in anunordered_map; O(n) in aflat_map. - Visit the elements in key order: a
mapand aflat_mapalways list them in order; anunordered_maplists them in an unspecified order. - Find the nearest key with
lower_bound: O(log n) in amapand aflat_map; anunordered_maphas no such function.
Four of these lines are worth reading twice:
- A vector has no
push_front. The standard gives sequence containerspush_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_mapfinds a key in O(log n), like amap, 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:
- 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.
Every measured count as a table
| n | Linear search: values checked | Binary search: probes |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 4 | 4 | 3 |
| 8 | 8 | 4 |
| 16 | 16 | 5 |
| 32 | 32 | 6 |
| 64 | 64 | 7 |
| 128 | 128 | 8 |
| 256 | 256 | 9 |
| 512 | 512 | 10 |
| 1,000 | 1,000 | 10 |
| 1,024 | 1,024 | 11 |
| 2,048 | 2,048 | 12 |
| 4,096 | 4,096 | 13 |
| 8,192 | 8,192 | 14 |
| 16,384 | 16,384 | 15 |
| 32,768 | 32,768 | 16 |
| 65,536 | 65,536 | 17 |
| 131,072 | 131,072 | 18 |
| 262,144 | 262,144 | 19 |
| 524,288 | 524,288 | 20 |
| 1,000,000 | 1,000,000 | 20 |
| 1,048,576 | 1,048,576 | 21 |
| 2,097,152 | 2,097,152 | 22 |
| 4,194,304 | 4,194,304 | 23 |
| 8,388,608 | 8,388,608 | 24 |
| 16,777,216 | 16,777,216 | 25 |
| 33,554,432 | 33,554,432 | 26 |
| 67,108,864 | 67,108,864 | 27 |
| 134,217,728 | 134,217,728 | 28 |
| 268,435,456 | 268,435,456 | 29 |
| 536,870,912 | 536,870,912 | 30 |
| 1,000,000,000 | 1,000,000,000 | 30 |
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
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:
// 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);
} 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:
vectorandflat_setrequested 524,288 bytes, 5.2 per element: the capacity doubled from 1 to 131,072 slots, which took 18 allocations. Areserve(100000)on the vector first would have made it one allocation of exactly 400,000 bytes; aflat_sethas noreserve, but it can be built from a vector reserved that way.dequealso 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.listrequested 24 bytes per element in both libraries, andforward_list16. A node holds theintand two pointers (list) or one (forward_list), padded to a multiple of 8 bytes, the alignment of a pointer.settook 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 theintinto the same 8 bytes, while libstdc++ gives the colour a padded 8-byte slot of its own.unordered_settook 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 anintand 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:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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
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::vectorof pairs sorted by key, searched withstd::ranges::lower_bound, a binary search; std::map;std::unordered_map;std::flat_map.
// 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);
}
} 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_mapwas 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::mapwas 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_mapstayed close to each other: both are binary searches over contiguous memory. At a million elementsflat_mapwas 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
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:
// 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;
} 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
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:
// 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);
}
} 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
Five rules make a measurement worth trusting
The measurements above follow five rules, and so should yours:
- Measure an optimised build, with the flags you ship. The examples use
-O2; a build without optimisation mostly measures debugging code. - 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.
- 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.
- Repeat, and keep the fastest run or look at the spread of many. Other programs only ever add time to a run.
- 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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
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 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.
- 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.
- Do you look values up by key, in any order? Yes: std::unordered_map or std::unordered_set.
- Do you add or remove elements at the front as well as at the back? Yes: std::deque.
- Must iterators survive insertions and erasures in the middle, or do you move runs of elements between lists? Yes: std::list.
- 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:
Answer the questions above: the table then marks what fits your case and says why the rest does not.
| 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
Checkpoint
Programs 4 to 6
Checkpoint
Programs 7 and 8
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.
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
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.
-
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?
-
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.
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:
mapis O(log n),unordered_mapis O(1) on average and O(n) at worst, andflat_mapfinds 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
intin alist, 32 or 40 in aset, depending on the library. - In the lookup timings,
unordered_mapwas the fastest at every size andstd::mapthe slowest from 10,000 elements up; the sorted vector andflat_mapwere 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
- Working Draft, Programming Languages: C++ (N4950), containers library (ISO/IEC JTC1/SC22/WG21)
- P0429R9: A Standard flat_map (ISO/IEC JTC1/SC22/WG21)
- C++ Core Guidelines, SL.con.2: Prefer using STL vector by default unless you have a reason to use a different container (Standard C++ Foundation)
- C++ Core Guidelines, Per.6: Don't make claims about performance without measurements (Standard C++ Foundation)
- C++ Core Guidelines, Per.19: Access memory predictably (Standard C++ Foundation)
- nanobench: simple, fast, accurate single-header microbenchmarking for C++ (nanobench project)
- libc++ C++23 Status (LLVM Project)
- C++ Standards Support in GCC (GNU Project)
Report a problem with this lesson
Kept only in this browser. Your Learn progress