C++ Standard Library C++ STL Library

C++ unordered_multimap - bucket() Function



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

As an unordered_multimap 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_multimap.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the unordered_multimap::bucket function returns the bucket number of the specified element of uMMap.

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

  for(auto& x: uMMap) {
    cout<<"["<<x.first<<": "<<x.second<<"]";   
    cout<<" is in bucket #"<<uMMap.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: Toronto] is in bucket #12.
[CAN: Ottawa] is in bucket #12.

❮ C++ <unordered_map> Library

5