In C++, std::unordered_map::reserve() prepares the table for about n elements.
It is the beginner-friendly way to tune an unordered_map: if you know you will insert many keys, reserve first. Include <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Pass the number of elements you plan to store.
C++
m.reserve(1000); // ready for about 1000 pairs
m.insert({"a", 1});
Call
What it does
m.reserve(n)
Ensure bucket_count is large enough for n elements under max_load_factor().
reserve(n) does not change size(). It only adjusts buckets. Unlike std::vector::reserve, there is no separate capacity() to read afterward; look at bucket_count() or load_factor().
Library declarations
C++
void reserve(size_type n);
Parameters
Parameter
Description
n
Expected number of elements to accommodate.
Return Value
Return Value
Description
void
Nothing. The table may grow.
C++ Examples
Example 1 — reserve() Before a Loop
Reserve room, then insert, and print the final size.