C++ .reserve()

mohit5upadhyay's avatar
Published Aug 6, 2025
Contribute to Docs

In C++, the .reserve() method reserves space for at least the specified number of elements in an unordered map, helping optimize performance by reducing costly rehash operations during bulk insertions.

  • 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

mapName.reserve(count);

Parameters:

  • count: The minimum number of elements to reserve space for.

Return value:

This is a void method. It doesn’t return a value but affects the internal capacity of the unordered map.

Example

This example demonstrates the use of the .reserve() method with an unordered map to optimize performance when adding student grades:

#include <iostream>
#include <unordered_map>
int main() {
// Initializing unordered_map and reserving space for 10 elements
std::unordered_map<std::string, int> studentGrades;
studentGrades.reserve(10);
// Adding student grades
studentGrades["Alice"] = 95;
studentGrades["Bob"] = 87;
studentGrades["Charlie"] = 92;
studentGrades["Diana"] = 88;
std::cout << "Student grades after reservation:\n";
for (const auto& student : studentGrades) {
std::cout << student.first << ": " << student.second << std::endl;
}
std::cout << "Bucket count: " << studentGrades.bucket_count() << std::endl;
return 0;
}

Here is the output:

Student grades after reservation:
Charlie: 92
Bob: 87
Diana: 88
Alice: 95
Bucket count: 11

Codebyte Example

This codebyte example demonstrates the use of the .reserve() method with an unordered map to store employee information efficiently:

Code
Output
Loading...

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