C++ unordered_set::bucket_count() 函数



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

语法

以下是 std::unordered_set::bucket_count() 函数的语法。

size_type bucket_count() const noexcept;

参数

此函数不接受任何参数。

返回值

此函数返回 unordered_set 中存在的桶的总数。

示例 1

让我们看下面的例子,我们将演示 unordered_set::bucket_count() 函数的使用。

#include <iostream>
#include <unordered_set>
using namespace std;
int main(void){
   unordered_set<char> uSet = {'a', 'b', 'c', 'd'};
   cout << "Number of buckets = " << uSet.bucket_count() << endl;
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Number of buckets = 13

示例 2

考虑下面的例子,我们将使用 unordered_set::bucket_count() 函数获取桶的总数以及项目的数量。

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main () {
   unordered_set<string> uSet = {"Aman","Garav", "Sunil", "Roja", "Revathi"};
   unsigned n = uSet.bucket_count();
   cout << "uSet has " << n << " buckets. \n";

   for (unsigned i=0; i<n; ++i) {
      cout << "bucket #" << i << " contains: ";
      for (auto it = uSet.begin(i); it!=uSet.end(i); ++it)
         cout << "[" << *it << "] ";
      cout << "\n";
   }
   return 0;
}

输出

以下是以上代码的输出:

uSet has 13 buckets. 
bucket #0 contains: 
bucket #1 contains: 
bucket #2 contains: 
bucket #3 contains: 
bucket #4 contains: 
bucket #5 contains: [Roja] [Garav] 
bucket #6 contains: 
bucket #7 contains: 
bucket #8 contains: [Aman] 
bucket #9 contains: 
bucket #10 contains: [Revathi] 
bucket #11 contains: 
bucket #12 contains: [Sunil] 

示例 3

在下面的示例中,我们将计算桶的数量,并使用 buckets_size() 计算每个桶中的元素数量。

#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
   unordered_set<char> uSet;
   uSet.insert({'a', 'b', 'c', 'd', 'e'});
   
   int n = uSet.bucket_count();
   cout << "uSet has " <<  n <<  " buckets.\n\n";
   
   for (int i = 0; i < n; i++) {
      if(uSet.bucket_size(i)>0)
         cout <<  "Bucket " <<  i <<  " has "<<  uSet.bucket_size(i) <<  " elements.\n";
   }
   return 0;
}

输出

以上代码的输出如下:

uSet has 13 buckets.

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

© . All rights reserved.