public member function
<unordered_map>

std:: unordered_map::bucket_count

size_type bucket_count() const noexcept;
返回桶的数量
返回 unordered_map 容器中的桶的数量。

桶是容器内部哈希表中用于根据其键的哈希值分配元素的槽。

桶的数量直接影响容器哈希表的 负载因子(以及因此发生的冲突的概率)。容器会自动增加桶的数量以将负载因子保持在特定阈值(其 max_load_factor)以下,每次需要增加桶的数量时都会导致 rehash

参数



返回值

当前的桶数量。

成员类型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
24
25
26
27
28
29
// unordered_map::bucket_count
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string> mymap = {
            {"house","maison"},
            {"apple","pomme"},
            {"tree","arbre"},
            {"book","livre"},
            {"door","porte"},
            {"grapefruit","pamplemousse"}
  };

  unsigned n = mymap.bucket_count();

  std::cout << "mymap has " << n << " buckets.\n";

  for (unsigned i=0; i<n; ++i) {
    std::cout << "bucket #" << i << " contains: ";
    for (auto it = mymap.begin(i); it!=mymap.end(i); ++it)
      std::cout << "[" << it->first << ":" << it->second << "] ";
    std::cout << "\n";
  }

  return 0;
}

可能的输出
mymap has 7 buckets.
bucket #0 contains: [book:livre] [house:maison] 
bucket #1 contains: 
bucket #2 contains: 
bucket #3 contains: [grapefruit:pamplemousse] [tree:arbre]
bucket #4 contains: 
bucket #5 contains: [apple:pomme]
bucket #6 contains: [door:porte]


复杂度

常量。

迭代器有效性

没有变化。

另见