C++ unordered_set reserve() Function
Example
Make room for 100 elements in an empty unordered set:
unordered_set<string> cars;
cars.reserve(100);
cout << "Size: " << cars.size() << "\n";
if (cars.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 set 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_set> 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_set.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 sets in our Unordered Set Tutorial.