C++ Standard Library C++ STL Library

C++ unordered_set - bucket() Function



The C++ unordered_set::bucket function returns the bucket number of the specified element of 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. Buckets are numbered from 0 to (bucket_count-1). 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 ( const key_type& k ) const;

Parameters

k Specify element whose bucket number is to be looked for.

Return Value

The bucket number of the specified element of the unordered_set.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the unordered_set::bucket function returns the bucket number of the specified element of uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{10, 20, 30, 40, 50, 60};

  for(const int& x: uSet)
    cout<<x<<" is in bucket #"<<uSet.bucket(x)<<".\n";   

  return 0;
}

The output of the above code will be:

60 is in bucket #4.
50 is in bucket #1.
40 is in bucket #5.
30 is in bucket #2.
20 is in bucket #6.
10 is in bucket #3.

❮ C++ <unordered_set> Library

5