public member function
<unordered_set>

std::unordered_set::max_load_factor

get (1)
float max_load_factor() const noexcept;
set (2)
void max_load_factor ( float z );
獲取或設定最大負載因子
第一個版本(1)返回容器的當前最大負載因子。
第二個版本(2)將 z 設定為容器的新最大負載因子。

負載因子是容器中的元素數量(其size)與桶數量(bucket_count)的比率。

預設情況下,容器具有max_load_factor1.0.

負載因子會影響雜湊表中發生衝突的機率(即兩個元素位於同一個桶中的機率)。容器使用max_load_factor作為強制增加桶數量(從而導致rehash)的閾值。

引數

z
新的最大負載因子

返回值

當前的負載因子(僅針對第一個過載版本)。

示例

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

int main ()
{
  std::unordered_set<std::string> myset =
  {"New York", "Paris", "London", "Hong Kong", "Bangalore", "Tel Aviv"};

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

  float z = myset.max_load_factor();
  myset.max_load_factor ( z / 2.0 );
  std::cout << "[max_load_factor halved]" << std::endl;

  std::cout << "new max_load_factor: " << myset.max_load_factor() << std::endl;
  std::cout << "new size: " << myset.size() << std::endl;
  std::cout << "new bucket_count: " << myset.bucket_count() << std::endl;
  std::cout << "new load_factor: " << myset.load_factor() << std::endl;

  return 0;
}

可能的輸出
current max_load_factor: 1
current size: 6
current bucket_count: 7
current load_factor: 0.857143
[max_load_factor halved]
new max_load_factor: 0.5
new size: 6
new bucket_count: 13
new load_factor: 0.461538


複雜度

常量。
可能會觸發 rehash(未包含)。

迭代器有效性

無變化,除非此值更改強制觸發了 rehash。在這種情況下,容器中的所有迭代器都將失效。

如果新容器的max_load_factor設定為低於當前load_factor,則會強制進行 rehash。

unordered_set 容器中元素的引用在所有情況下都保持有效,即使在 rehash 之後也是如此。

另見