The unordered_multimap::reserve() is a built-in function in C++ STL which sets the number of buckets in the container (bucket_count) to the most appropriate number so that it contains at least n elements. If n is greater than the current bucket_count multiplied by the max_load_factor, the container’s bucket_count is increased and a rehash is forced. By calling reserve with the size that was expected for the unordered_multimap container, the multiple rehashes can be avoided. The multiple rehashes are those that are produced due to increase in container size which optimizes the size of the hash table. If n is lower than that, the function may have no effect.
Syntax:
unordered_multimap_name.reserve(N)
Parameters: The function accepts a single mandatory parameter N which specifies the number of elements requested as the minimum capacity.
Return Value: The function does not return anything.
Below programs illustrates the above function:
Program 1:
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_multimap< int , int > sample1, sample2;
sample1.reserve(1);
sample1.insert({ 10, 100 });
sample1.insert({ 50, 500 });
sample2.reserve(3);
sample2.insert({ 20, 200 });
sample2.insert({ 30, 300 });
sample2.insert({ 30, 150 });
cout << "The size of Sample1 is: " << sample1.size();
cout << "\nKey and Elements of Sample1 are:" ;
for ( auto it = sample1.begin(); it != sample1.end(); it++) {
cout << "{" << it->first << ", " << it->second << "} " ;
}
cout << "\n\nThe size of Sample2 is: " << sample2.size();
cout << "\nKey and Elements of Sample2 are:" ;
for ( auto it = sample2.begin(); it != sample2.end(); it++) {
cout << "{" << it->first << ", " << it->second << "} " ;
}
return 0;
}
|
Output:
The size of Sample1 is: 2
Key and Elements of Sample1 are:{50, 500} {10, 100}
The size of Sample2 is: 3
Key and Elements of Sample2 are:{30, 150} {30, 300} {20, 200}
Program 2:
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_multimap< char , char > sample1, sample2;
sample1.reserve(1);
sample1.insert({ 'a' , 'A' });
sample1.insert({ 'g' , 'G' });
sample2.reserve(3);
sample2.insert({ 'b' , 'B' });
sample2.insert({ 'c' , 'C' });
sample2.insert({ 'd' , 'D' });
cout << "The size of Sample1 is: " << sample1.size();
cout << "\nKey and Elements of Sample1 are:" ;
for ( auto it = sample1.begin(); it != sample1.end(); it++) {
cout << "{" << it->first << ", " << it->second << "} " ;
}
cout << "\n\nThe size of Sample2 is: " << sample2.size();
cout << "\nKey and Elements of Sample2 are:" ;
for ( auto it = sample2.begin(); it != sample2.end(); it++) {
cout << "{" << it->first << ", " << it->second << "} " ;
}
return 0;
}
|
Output:
The size of Sample1 is: 2
Key and Elements of Sample1 are:{g, G} {a, A}
The size of Sample2 is: 3
Key and Elements of Sample2 are:{d, D} {c, C} {b, B}