In C++, std::unordered_set::reserve() prepares the table for about n elements.
It is the beginner-friendly way to tune an unordered_set: if you know you will insert many keys, reserve first. Include <unordered_set> to use it.
This is a member of std::unordered_set<T>, a hash table of unique values. Find, insert, and erase are usually average constant time. Unlike std::set, values are not sorted and iteration order is unspecified. Elements are const, so you cannot change a stored value through an iterator. There is no operator[] and no at(). Prefer find() or contains() to look up a value, and call reserve() before many inserts.
Syntax
Pass the number of elements you plan to store.
C++
m.reserve(1000); // ready for about 1000 values
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.