public member function
<unordered_map>

std::unordered_multimap::reserve

void reserve( size_type n );
請求容量更改
將容器的桶數(bucket_count)設定為最適合容納至少 n 個元素的數值。

如果 n 大於當前bucket_count 乘以max_load_factor,則會增加容器的bucket_count並強制執行rehash

如果 n 低於該值,則函式可能無效。

引數

n
請求的最小容量元素數。
成員型別size_type是無符號整數型別

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// unordered_multimap::reserve
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{

  std::unordered_multimap<std::string,std::string> myumm;

  myumm.reserve(7);

  myumm.insert({{"apple","NY"},{"apple","WA"},{"peach","GA"}});
  myumm.insert({{"orange","FL"},{"cherry","UT"}});
  myumm.insert({{"strawberry","LA"},{"strawberry","NC"}});

  for (auto& x: myumm) {
    std::cout << x.first << ": " << x.second << std::endl;
  }

  return 0;
}

可能的輸出
strawberry: LA
strawberry: NC
cherry: UT
orange: FL
apple: NY
apple: WA
peach: GA


透過呼叫reserve並指定我們預期的 unordered_multimap 容器的大小,我們避免了容器大小增加可能產生的多次重新雜湊(rehash),並優化了雜湊表的大小。

複雜度

在重新雜湊的情況下,
平均情況:與容器大小成線性關係。
最壞情況:與容器大小成二次方關係。

迭代器有效性

如果發生重新雜湊,所有迭代器都會失效,但指向單個元素的引用和指標仍然有效。
如果沒有實際發生重新雜湊,則無變化。

另見