C++ unordered_map::bucket_size() 函数



C++ 函数unordered_map::bucket_size() 返回第 n 个桶中存在的元素数量。桶是容器内部哈希表中的一个槽,元素根据其键的哈希值分配到该槽中。桶的编号范围从 0 到 (bucket_count - 1)。

此函数返回每个桶中的元素数量,该数量始终小于总数。

语法

以下是 unordered_map::bucket_size() 函数的语法。

unordered_map.bucket_size(n);

参数

  • n - 指示桶号,它是一个无符号整数,应小于 bucket_count。

返回值

返回一个无符号整数,表示当前桶中元素的总数。

示例 1

以下示例将使用 unordered_map::bucket_size()。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void){
   unordered_map<char, int> um ={
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   for (int i = 0; i < um.bucket_count(); ++i)
      cout << "Bucket " << i << " contains "<< um.bucket_size(i) << " elements." << endl;
   return 0;
}

输出

以上代码的输出如下:

Bucket 0 contains 0 elements.
Bucket 1 contains 0 elements.
Bucket 2 contains 0 elements.
Bucket 3 contains 0 elements.
Bucket 4 contains 0 elements.
Bucket 5 contains 0 elements.
Bucket 6 contains 1 elements.
Bucket 7 contains 1 elements.
Bucket 8 contains 1 elements.
Bucket 9 contains 1 elements.
Bucket 10 contains 1 elements.
Bucket 11 contains 0 elements.
Bucket 12 contains 0 elements.

示例 2

考虑以下示例,我们将计算桶的数量。

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main () {
   std::unordered_map<std::string,std::string> map = {
      {"us","United States"},
      {"uk","United Kingdom"},
      {"fr","France"},
   };
   unsigned totalbuckets = map.bucket_count();
   unsigned element = map.bucket_size(9);
   cout<<"total number of buckets"<<": "<<totalbuckets<<endl;
   cout << "bucket 9 has " << element << " element:\n";
   return 0;
}

输出

以上代码的输出如下:

total number of buckets: 13
bucket 9 has 1 element:

示例

在以下示例中,我们获取当前 unordered_map 中至少包含一个元素的桶的数量及其元素大小。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   for (int i = 0; i < um.bucket_count(); ++i) {
      if(um.bucket_size(i)>0) {
         cout << "Bucket " << i << " contains "<< um.bucket_size(i) << " elements." << endl;
      }
   }
   return 0;
}

输出

让我们编译并运行以上程序,这将产生以下结果:

Bucket 6 contains 1 elements.
Bucket 7 contains 1 elements.
Bucket 8 contains 1 elements.
Bucket 9 contains 1 elements.
Bucket 10 contains 1 elements.
广告