man cpp/unordered-map

How std::unordered_map works, and why it can't be flat

lib / C++ 11 mindraft

checked against: libc++ 22.1.6, libstdc++ (GCC 15.2.0)

std::unordered_map is C++’s standard hash table, and every element of it is a separate heap allocation. Hash tables that keep their elements in one array, probing for a free slot on a collision, are a well-known alternative. Why doesn’t the standard library use that design?

This article reads the hash table in LLVM’s libc++ at tag llvmorg-22.1.6, the version Apple clang 21 reports on my Mac (_LIBCPP_VERSION is 220106). Apple builds its own copy, so I compared the headers: __hash_table, unordered_map and __functional/hash.h in the macOS SDK are byte-for-byte identical to the upstream tag. The parts compiled into the shared library, such as __next_prime, I could only read in the upstream source. For contrast I also read GNU libstdc++ at releases/gcc-15.2.0. I have no libstdc++ toolchain on this Mac, so everything about it here comes from reading source, not from running it.

The layout: one list, many buckets

The table lives in include/__hash_table. Its data members are four fields (L670-675):

  • __bucket_list_: an array of pointers, one per bucket, plus its length;
  • __first_node_: a bare next pointer that acts as the node before the first element;
  • __size_: the element count;
  • __max_load_factor_: a float, initialised to 1.0f (L1069).

On a 64-bit Mac that is 8 bytes each for the bucket pointer, the bucket count, the first-node pointer and the size, plus a 4-byte float padded to 8: 40 bytes, and sizeof(std::unordered_map<int, int>) printed 40. The elements are not in the bucket array. Each one is a separately allocated node (L128-165) holding a __next_ pointer, the cached hash value __hash_ (L134), and the pair<const Key, T>.

All the nodes form one singly linked list that starts at __first_node_. Each bucket stores a pointer to the node before its first element, so that inserting or erasing at the front of a bucket can relink the previous node without a doubly linked list. Elements of one bucket sit next to each other in the big list:

__first_node_ -> [45] -> [78] -> [43] -> [76] -> [55] -> [57] -> null
                  b1      b1      b10     b10     b0      b2

bucket 0  -> points at [76]           (the node before 55)
bucket 1  -> points at __first_node_  (the node before 45)
bucket 2  -> points at [55]           (the node before 57)
bucket 10 -> points at [78]           (the node before 43)

The picture comes from a real run. It shows the iteration order and the bucket numbers I got after counting 57 55 76 78 45 43 into an empty map (11 buckets). Iteration is a walk down the list, so going from begin() to end() never visits an empty bucket.

Matthew Austern’s 2003 proposal for standard hash tables (N1456) describes this “single long list” in its section on iterators, as the easy option for doubly linked lists. For singly linked lists he wrote: “I don’t know of a way to make the single-long-list technique work for singly linked lists”, because erasing a node needs the node before it. Storing the node before the bucket’s first element is how libc++ gets around that.

A new element in a bucket that already has entries goes in right after the bucket’s “before” pointer. A new element in an empty bucket goes to the very front of the whole list, and the bucket that used to be first gets its pointer fixed up (L805-819). That is why the most recently started buckets come first when you iterate.

What one insert costs

operator[] is __emplace_unique(piecewise_construct, ...) (include/unordered_map L1553-1556). The insert path (__hash_table L776-830) does this:

  1. Hash the key and reduce it to a bucket index.
  2. Walk that bucket’s nodes. For each node it compares the cached hash first and calls == only when the hashes match. The walk stops at the first node whose hash reduces to a different bucket.
  3. If the key is found, return it. Nothing is allocated.
  4. Otherwise allocate the node. If size() + 1 > bucket_count() * max_load_factor(), rehash first. Then link the node in.

Caching the hash means a rehash never calls the hash function again, and a lookup rarely calls == on the wrong key. The cost is 8 bytes per node. libstdc++ makes the opposite choice for cheap hashes: its __cache_default (bits/hashtable.h L54-58) turns caching off when __is_fast_hash<Hash> is true, and that trait is true by default and false for long double (bits/functional_hash.h L298-303) and for the string hashes (bits/basic_string.h L4957-4962).

I counted the allocations with a logging allocator:

$ ./mapnode
map: allocate 40 bytes
map: allocate 40 bytes
unordered_map: allocate 24 bytes
unordered_map: allocate 16 bytes
unordered_map: allocate 24 bytes
unordered_map: allocate 24 bytes
unordered_map: allocate 40 bytes

An unordered_map<int, int> node is 24 bytes: next pointer, hash, two ints. The 16 and 40 are bucket arrays of 2 and 5 pointers. The node is allocated before the bucket array, exactly in the order of step 4. A std::map<int, int> node is 40 bytes: left, right and parent pointers, a colour flag, and the pair.

std::hash<int> is the identity

For integral types no wider than size_t, libc++’s std::hash is one line (__functional/hash.h L372):

size_t operator()(_Tp __v) const _NOEXCEPT { return static_cast<size_t>(__v); }

So std::hash<int>{}(57) is 57, and std::hash<int>{}(-1) is 18446744073709551615. libstdc++ does the same with a macro, _Cxx_hashtable_define_trivial_hash (bits/functional_hash.h L118-124, used for int at L157). The standard asks for much less than a good hash: only that equal keys hash equally and that the call doesn’t throw ([unord.hash]).

An identity hash puts all the burden on the step from hash to bucket. libc++ does it in __constrain_hash (L169-171):

return !(__bc & (__bc - 1)) ? __h & (__bc - 1) : (__h < __bc ? __h : __h % __bc);

With a power-of-two bucket count it keeps the low bits. Otherwise it takes the remainder, and skips the division when the hash is already smaller than the bucket count. With small non-negative keys and the identity hash, key 57 simply lives in bucket 57 once the table is bigger than that.

Bucket counts: primes, unless you ask

When an insert would push the load factor over the maximum, the table grows to max(2 * bc + !__is_hash_power2(bc), ceil((size + 1) / max_load_factor)) buckets (L799-802). __rehash (L1709-1726) then rounds any count that is not a power of two up to the next prime with __next_prime (src/hash.cpp L64), which uses a table of primes below 212 and, above that, trial division of candidates of the form 210k + i.

I printed bucket_count() while inserting 0, 1, 2, … into an empty map (output shortened where marked ...):

$ ./buckets
empty: 0 buckets
size      1 -> 2 buckets
size      3 -> 5 buckets
size      6 -> 11 buckets
size     12 -> 23 buckets
size     24 -> 47 buckets
size     48 -> 97 buckets
...
size  25718 -> 51437 buckets
size  51438 -> 102877 buckets
rehash(1024): 1024 buckets
after 5000 inserts: 8192 buckets
reserve(1000): 1009 buckets

Each step is 2 × count + 1, rounded up to a prime. A power of two is a special case. rehash(1024) keeps exactly 1024, and from then on 2 * bc + 0 stays a power of two (8192 after 5000 inserts), so the table uses the cheap mask instead of %. __is_hash_power2 (L167) requires more than 2 buckets, so the 2-bucket table after the first insert doesn’t get locked into powers of two.

The prime default is the safe choice for an identity hash. With a mask, only the low bits of the key matter, and keys that share them pile into one bucket:

$ ./umap_demo | tail -2
keys 0, 1024, 2048, ... x20000, default: 25717 buckets, longest bucket 1, 0.3 ms
keys 0, 1024, 2048, ... x20000, after rehash(1024): 32768 buckets, longest bucket 625, 51.6 ms

Same keys, same hash, over a hundred times slower, because I asked for a power of two once.

libstdc++ also uses primes by default. std::unordered_map is declared with _Prime_rehash_policy (bits/unordered_map.h L55-61), which picks the next prime from a fixed table (src/shared/hashtable-aux.cc L28; its comment gives the size as “256 + 1 or 256 + 48 + 1”) and grows by _S_growth_factor = 2 (bits/hashtable_policy.h L640). A _Power2_rehash_policy exists in the same file (L673) but std::unordered_map doesn’t use it. On the first insert into an empty table, a comment in src/c++11/hashtable_c++0x.cc (L96-121) says “we start with an initial bucket size of 11”.

Why it can’t be flat

The fast tables people compare it to store elements directly in one array and probe neighbouring slots on a collision. Three rules in the standard rule that out for std::unordered_map. I cite the current working draft on eel.is (generated 2026-08-23).

References survive rehashing. [unord.req.general] paragraph 9: “Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.” Paragraph 242 repeats it for every insert and emplace. In an open-addressing table a rehash moves every element to a new array, so every reference would dangle. Only a design where each element has its own fixed address can keep this promise.

I checked it with a pointer to the count of key 57, taken while the map had 11 buckets:

$ ./umap_demo | sed -n 4p
after growing to 102877 buckets, the int at the old address is 1 (m[57] = 1, same address: yes)

The pointer is still valid after 100,000 more inserts and 13 rehashes.

Node handles. extract removes an element and hands you a node_type that owns it, and insert puts it back, into the same map or another one, without copying the value (paragraph 244: pointers and references to the extracted element stay valid). That requires the element to live in its own allocation.

The bucket interface. bucket(k) and begin(n)/end(n) must run in constant time, and begin(n) returns a local_iterator that “can be used to iterate through a single bucket”. bucket_size(n) may take time proportional to the bucket’s size. With open addressing a “bucket” has no meaning: a key’s elements are spread along a probe sequence shared with other keys.

None of these says “linked list” in so many words. Together they describe separate chaining, which is what Austern’s proposal assumed. Its section “Chaining Versus Open Addressing” says: “I’m not aware of any satisfactory implementation of open addressing in a generic framework”, and lists the problems: telling vacant slots from occupied ones, constructing elements ahead of time, collision management, erasure, and growth. “All further discussion will assume chaining.”

The cost is visible in my counting benchmark. Counting 100,000 integers drawn from 50,000 values takes 2.5 ms with std::unordered_map, and 1.2 ms when I call reserve first so it never rehashes. Every one of the 43,282 distinct keys costs a 24-byte allocation, and every lookup follows pointers from the bucket array into the nodes. Copying the resulting 43,282 entries into a vector took 284 µs, longer than sorting them, because iteration follows the list from node to node.

What about std::flat_map?

C++23 added std::flat_map, and libc++ has it. Its C++23 status page marks P0429R9 complete in version 20. It compiles with -std=c++23 here. The standard calls it “a container adaptor” over a key container and a value container, keeps the keys sorted, and says that inserting or erasing a single element takes linear time ([flat.map.overview]). libc++ looks keys up with lower_bound on the sorted keys. Counting the same 100,000 integers into one took 65 ms, 26 times longer than unordered_map, because about 43,000 of those operations insert into the middle of two vectors.

Curious facts

  • std::hash<int>{}(-1) is 18446744073709551615 in libc++. The cast to size_t keeps the bit pattern.
  • max_load_factor(z) never lowers the limit below the current load: libc++ stores max(z, load_factor()) (__hash_table L962-968).
  • A default-constructed unordered_map has 0 buckets and allocates nothing. The first insert creates 2.
  • reserve(1000) gives 1009 buckets, the first prime after 1000.
  • libc++ and libstdc++ disagree on whether a node stores its hash. libc++ always does; libstdc++ does only when the hash isn’t marked fast, which for the standard hashes means long double and the string types.

History

versionchangeevidence
2003Austern’s proposal N1456 (revision 4) for hash tables, chaining by design, with a bucket interfaceN1456
LLVM 20libc++ completes std::flat_map (P0429R9)libc++ 20 release notes; C++23 status page
LLVM 22libc++ speeds up copying unordered_set (3.3×), its copy assignment (5×) and range erase of the unordered containers (1.9×)libc++ 22 release notes

Sources

libc++ at llvmorg-22.1.6:

libstdc++ at releases/gcc-15.2.0:

Standard (working draft on eel.is, generated 2026-08-23):

Papers:

ls cpp/