C++ unordered_set - bucket_count() Function
The C++ unordered_set::bucket_count function returns the number of buckets in the unordered_set.
As an unordered_set is implemented using hash table where a bucket is a slot in the container's internal hash table to which elements are assigned based on the hash value. The number of buckets directly influences the load_factor of the container's hash table. The container automatically increases the number of buckets to keep the load_factor below its max_load_factor which causes rehash whenever the number of buckets is increased.
Syntax
size_type bucket_count() const noexcept;
Parameters
No parameter is required.
Return Value
Number of buckets in the unordered_set.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the unordered_set::bucket_count function returns the number of buckets in uSet.
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_set<int> uSet{55, 25, 128, 5, 72, -500, 45, 24, -20}; cout<<"uSet contains "<<uSet.bucket_count()<<" buckets:"; for(unsigned int i = 0; i < uSet.bucket_count(); i++) { cout<<"\nThe bucket #"<<i<<" contains: "; for(auto it = uSet.begin(i); it != uSet.end(i); ++it) { cout<<*it<<" "; } } return 0; }
The output of the above code will be:
uSet contains 11 buckets: The bucket #0 contains: -500 55 The bucket #1 contains: 45 The bucket #2 contains: 24 The bucket #3 contains: 25 The bucket #4 contains: The bucket #5 contains: 5 The bucket #6 contains: 72 The bucket #7 contains: -20 128 The bucket #8 contains: The bucket #9 contains: The bucket #10 contains:
❮ C++ <unordered_set> Library