C++ unordered_map reserve() Function
Example
Make room for 100 elements in an empty unordered map:
unordered_map<string, int> people;
people.reserve(100);
cout << "Size: " << people.size() << "\n";
if (people.bucket_count() >= 100) {
cout << "There is room for 100 elements";
}
Definition and Usage
The reserve() function makes room for at least the given number of elements. It sets the number of buckets (groups that hold elements), so that the unordered map does not need to add more buckets while you add the elements.
It does not add any elements, so the size does not change.
The reserve function is defined in the <unordered_map> header file.
Tip: Use reserve() before you add many elements. This can make your program faster. The rehash() function does almost the same, but you give it the number of buckets instead of the number of elements.
Syntax
unordered_map.reserve(n)
Parameter Values
| Parameter | Description |
|---|---|
| n | Required. The number of elements to make room for. |
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.