C++ Unordered_set::max_bucket_count() Function



The C++ unordered_set::max_bucket_count() function is used to return the maximum number of buckets held by the unordered_set container due to system and library implementation limitations. 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. It has a numbers ranging from 0 to bucket_count - 1.

Syntax

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

size_type bucket_count() const noexcept;

Parameters

This function does not accepts any parameter.

Return Value

This function returns the maximum number of buckets in the unordered_set.

Example 1

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

#include <iostream>
#include <unordered_set>
using namespace std;

int main(void){
   unordered_set<char> uSet = {'a', 'b', 'c', 'd'};
   cout << " Maximum Number of buckets = " << uSet.max_bucket_count() << endl;
   return 0;
}

Output

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

Maximum Number of buckets = 576460752303423487

Example 2

Consider the following example, where we are going to get the the maximum number of buckets and also displaying the total number of buckets.

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

int main () {
   unordered_set<string> uSet = {"Aman","Garav", "Sunil", "Roja", "Revathi"};
   unsigned max = uSet.max_bucket_count();
   cout << "uSet has maximum: " << max << " buckets. \n"; 
   unsigned n = uSet.bucket_count();
   cout << "uSet has total number of bucket: "<< n <<" buckets. \n";
   return 0;
}

Output

Following is the output of the above code −

uSet has maximum:2863311530 buckets. 
uSet has total number of bucket: 13 buckets. 

Example 3

In the following example, we are going to consider the two unordered_sets one is emempty and another with elements and applying the unordered_set::max_bucket_count() and bucket_count() functions.

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<char> uSet;
   uSet.insert({'a', 'b', 'c', 'd'});
   unordered_set<char> myUSet;
   
   unsigned max1 = uSet.max_bucket_count();
   int n1 = uSet.bucket_count();
   cout << "uSet has maximum: " <<  max1 <<  " buckets.\n";
   cout << "uSet has: " << n1 << " buckets. \n";
 
   unsigned max2 = myUSet.max_bucket_count();
   int n2 = myUSet.bucket_count();
   cout << "myUSet has maximum: " <<  max2 <<  " buckets.\n";
   cout << "myUSet has: " << n2 << " buckets. \n";
   
   return 0;
}

Output

Output of the above code is as follows −

uSet has maximum: 4294967295 buckets.
uSet has: 13 buckets. 
myUSet has maximum: 4294967295 buckets.
myUSet has: 1 buckets. 
Advertisements