C++ Standard Library C++ STL Library

C++ unordered_multimap - bucket_size() Function



The C++ unordered_multimap::bucket_size function returns the number of elements in the specified bucket 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. 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_size ( size_type n ) const;

Parameters

n Specify the bucket number.

Return Value

Number of elements in the bucket number n of the unordered_multimap.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the unordered_multimap::bucket_size function returns the number of elements in the specified bucket 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"}};

  cout<<"uMMap contains "<<uMMap.bucket_count()<<" buckets:";

  for(unsigned int i = 0; i < uMMap.bucket_count(); i++)
    cout<<"\nBucket #"<<i<<" contains: "<<uMMap.bucket_size(i)<<" elements.";   

  return 0;
}

The output of the above code will be:

uMMap contains 13 buckets:
Bucket #0 contains: 0 elements.
Bucket #1 contains: 0 elements.
Bucket #2 contains: 0 elements.
Bucket #3 contains: 0 elements.
Bucket #4 contains: 0 elements.
Bucket #5 contains: 0 elements.
Bucket #6 contains: 0 elements.
Bucket #7 contains: 0 elements.
Bucket #8 contains: 0 elements.
Bucket #9 contains: 0 elements.
Bucket #10 contains: 1 elements.
Bucket #11 contains: 1 elements.
Bucket #12 contains: 2 elements.

❮ C++ <unordered_map> Library

5