unordered_multimap reserve() function in C++ STL

C++Server Side ProgrammingProgramming

The unordered_multimap reserve() function in C++ STL sets the number of buckets in the container to the most appropriate number so that it contains at least n elements.

If n is greater than the current numbers of bucket multiplied by the max_load_factor, the container’s number of buckets is increased and a rehash is forced.

Reserve () returns nothing and take n as a parameter which specifies the minimum number of elements as per requested minimum capacity.

Algorithm

Begin
   Declare the vector m.
   m.reserve(6) = the size is reserved for the bucket to contain minimum number of one elements.
   Insert the key value pairs.
   Print the result.
End.

Example Code

 Live Demo

#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
   unordered_map<char, int> m;      //declaring m as map container

   m.reserve(6);//restricting the most appropriate value of
   m.insert (pair<char, int>('b', 10)); // inserting values
   m.insert (pair<char, int>('a', 20));

   cout << "The size is: " << m.size();
   cout << "\nKey and values are: ";
   for (auto it = m.begin(); it != m.end(); it++) {
      cout << "{" << it->first << ", " << it->second << "} "; //printing the values of map container
   }
   return 0;
}

Output

The size is: 2
Key and values are: {a, 20} {b, 10}
raja
Published on 02-Apr-2019 18:00:44
Advertisements