In this shot, we’ll learn about the unordered_map::reserve()
function in C++.
The unordered_map::reserve()
function is available in the <unordered_map>
header file in C++.
The unordered_map::reserve()
function is used to reserve the number of buckets in the unordered map to store at least n elements inside the map. If the bucket count cannot hold n elements, then the bucket count is increased and a rehashing occurs.
The syntax of the unordered_map::reserve()
function is given below:
void reserve(size_type n);
The unordered_map::reserve()
function accepts only one parameter, that is, the minimum number of elements that we want the unordered map to hold. In other words, the parameter specifies the number of buckets to hold a minimum of n elements in the map.
The unordered_map::reserve()
function returns no values.
Let’s look at the code below:
#include <iostream>#include <unordered_map>using namespace std;int main (){unordered_map<int, string> umap;cout << "Bucket Count: " << umap.bucket_count() << endl;umap.reserve(6);cout << "Bucket Count after reserve(): " << umap.bucket_count() << endl;umap[1] = "Welcome";umap[2] = "to";umap[3] = "Educative";umap[4] = "Learn";umap[5] = "Programming";for (auto& i: umap)cout << i.first << "->" << i.second << endl;return 0;}
Lines 1 and 2: We import the required header files.
Line 7: We define an unordered map.
Line 9: We print the current bucket count using the unordered_map::bucket_count()
function.
Line 11: We call the unordered_map::reserve()
function to make the bucket count to store at least elements.
Line 13: We again print the bucket count. Here, we can see in the output that the bucket count is increased to hold a minimum of elements.
Lines 15 to 19: We add some elements to the map.
Lines 20 and 21: We print the elements present in the unordered map.
So, in this way, we can make reservations of the buckets to hold a minimum of n elements in the unordered map.