C++ .reserve()
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.
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 elementsstd::unordered_map<std::string, int> studentGrades;studentGrades.reserve(10);// Adding student gradesstudentGrades["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: 92Bob: 87Diana: 88Alice: 95Bucket count: 11
Codebyte Example
This codebyte example demonstrates the use of the .reserve() method with an unordered map to store employee information efficiently:
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