C++ Standard Library C++ STL Library

C++ unordered_map - bucket() Function



The C++ unordered_map::bucket function returns the bucket number of the specified element of the unordered_map.

As an unordered_map 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 of their key. 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_map.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the unordered_map::bucket function returns the bucket number of the specified element of uMap.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_map<string, string> uMap;
  uMap = {{"CAN", "Ottawa"}, {"USA", "Washington"}, {"IND", "Delhi"}};

  for(auto& x: uMap) {
    cout<<"["<<x.first<<": "<<x.second<<"]";   
    cout<<" is in bucket #"<<uMap.bucket(x.first)<<".\n";
  }

  return 0;
}

The output of the above code will be:

[IND: Delhi] is in bucket #11.
[USA: Washington] is in bucket #10.
[CAN: Ottawa] is in bucket #12.

❮ C++ <unordered_map> Library