public member function
<unordered_set>

std::unordered_set::rehash

void rehash ( size_type n );
設定桶的數量
將容器中的桶數設定為 n 或更多。

如果 n 大於容器當前的桶數(bucket_count),則強制進行重雜湊。新的桶數可以等於或大於 n

如果 n 小於容器當前的桶數(bucket_count),則該函式可能不會影響桶數,並且可能不會強制進行重雜湊。

重雜湊是對雜湊表的重建:容器中的所有元素都根據它們的雜湊值重新排列到新的桶集中。這可能會改變容器內元素的迭代順序。

當容器的負載因子在其操作中將超過其最大負載因子時,容器會自動執行重雜湊。

請注意,此函式將桶數作為引數。存在一個類似的函式 unordered_set::reserve,它以容器中的元素數為引數。

引數

n
容器雜湊表的最小桶數。
成員型別size_type是一種無符號整型型別。

返回值



示例

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

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

  myset.rehash(12);

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

  std::cout << "current bucket_count: " << myset.bucket_count() << std::endl;

  return 0;
}

可能的輸出
current bucket_count: 13


透過呼叫rehash透過預留一定數量的最小桶數到雜湊表中,我們可以避免容器擴充套件可能引起的多次重新雜湊。

複雜度

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

迭代器有效性

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

另見