C++ reserve()

Anonymous contributor's avatar
Anonymous contributor
Published Jan 30, 2026
Contribute to Docs

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.

  • 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

Syntax

unordered_set_name.reserve(n);

Parameters:

  • n (size_type): Minimum number of elements the container should be able to accommodate without exceeding max_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: 3
Buckets after: 11
Max load factor: 1
Load factor: 0.272727
Size: 7
Buckets final: 11

Codebyte Example

This example demonstrates reserve() with strings, and prints capacity-related information:

Code
Output

All contributors

Contribute to 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