public member function
<unordered_set>

std::unordered_set::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
23
// unordered_set::reserve
#include <iostream>
#include <string>
#include <unordered_set>

int main ()
{
  std::unordered_set<std::string> myset;

  myset.reserve(5);

  myset.insert("office");
  myset.insert("house");
  myset.insert("gym");
  myset.insert("parking");
  myset.insert("highway");

  std::cout << "myset contains:";
  for (const std::string& x: myset) std::cout << " " << x;
  std::cout << std::endl;

  return 0;
}

可能的輸出
myset contains: highway house office gym parking


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

複雜度

在重新雜湊的情況下,
平均情況:線性於 容器大小
最壞情況:二次於 容器大小

迭代器有效性

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

另見