C ++ STL中的unordered_multimap reserve()函数

reserve()C ++ STL中的unordered_multimap函数将容器中的存储桶数量设置为最合适的数量,以便它至少包含n个元素。

如果n大于当前存储桶数乘以max_load_factor,则将增加容器的存储桶数,并强制进行重新哈希。

Reserve()不返回任何内容,并以n作为参数,该参数指定根据请求的最小容量的最小元素数。

算法

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.

范例程式码

#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;
}

输出结果

The size is: 2
Key and values are: {a, 20} {b, 10}