C++ reserve()
The reserve() method requests a capacity change for an std::unordered_set. It sets the number of buckets to the amount needed to accommodate at least n elements without exceeding the container’s max_load_factor(). Calling reserve(n) may trigger a rehash; if it does, all iterators are invalidated, but references and pointers to elements remain valid. This operation does not sort elements or impose any ordering.
Syntax
unordered_set_name.reserve(n);
Parameters:
n(size_type): Minimum number of elements the container should be able to accommodate without exceedingmax_load_factor().
Return value:
This method doesn’t return anything (void).
Example
This example shows bucket capacity before and after reserve(), and demonstrates that elements remain accessible with the same unordered iteration semantics:
#include <iostream>#include <unordered_set>using namespace std;int main() {unordered_set<int> numbers = {10, 20, 30};cout << "Buckets before: " << numbers.bucket_count() << "\n";numbers.reserve(10);cout << "Buckets after: " << numbers.bucket_count() << "\n";cout << "Max load factor: " << numbers.max_load_factor() << "\n";cout << "Load factor: " << numbers.load_factor() << "\n";for (int i = 1; i <= 7; ++i) {numbers.insert(i * 5);}cout << "Size: " << numbers.size() << "\n";cout << "Buckets final: " << numbers.bucket_count() << "\n";return 0;}
The output of this code is:
Buckets before: 3Buckets after: 11Max load factor: 1Load factor: 0.272727Size: 7Buckets final: 11
Codebyte Example
This example demonstrates reserve() with strings, and prints capacity-related information:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours