C++ unordered_set::bucket_count() Function



The C++ unordered_set::bucket_count() function is used to return the number of buckets in the unordered_set container. A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash value of their key. They have a number ranging from 0 to bucket_count - 1.

Syntax

Following is the Syntax of std::unordered_set::bucket_count() function.

size_type bucket_count() const noexcept;

Parameters

This function does not accepts any parameter.

Return Value

This function returns the total number of bucket present in the unordered_set.

Example 1

Let's look at the following example, where we are going to demonstrate the usage of unordered_set::bucket_count() function.

#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;
}

Output

If we run the above code it will generate the following output −

Number of buckets = 13

Example 2

Consider the following example, where we are going to use the unordered_set::bucket_count() function to get the total number of buckets alongs with a no.of items.

#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;
}

Output

Following is the output of the above code −

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] 

Example 3

In the following example, we are going to count the number of buckets and buckets_size() to count the number of elements in each bucket.

#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;
}

Output

Output of the above code is as follows −

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.
Advertisements