C++ Standard Library C++ STL Library

C++ unordered_map - max_load_factor() Function



The C++ unordered_map::max_load_factor function is used to either return or set the current maximum load factor of the unordered_map. The load_factor is defined as ratio of number of elements (its size) in the container and number of buckets in the container (its bucket_count).

By default, the max_load_factor of unordered_map is 1.0.

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. 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

//version 1
float max_load_factor() const noexcept;

//version 2
void max_load_factor (float z);

Parameters

z Specify the new maximum load factor.

Return Value

The current load factor of the unordered_map (version 1).
None (version 2).

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the unordered_map::max_load_factor function is used to find out the current max_load_factor of uMap

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

  cout<<"Size = "<<uMap.size()<<"\n";
  cout<<"Bucket count = "<<uMap.bucket_count()<<"\n";
  cout<<"load factor = "<<uMap.load_factor()<<"\n";  
  cout<<"Max load factor = "<<uMap.max_load_factor()<<"\n";

  cout<<"\nmax_load_factor is changed.\n\n";
  uMap.max_load_factor(1.5);

  cout<<"Size = "<<uMap.size()<<"\n";
  cout<<"Bucket count = "<<uMap.bucket_count()<<"\n";
  cout<<"load factor = "<<uMap.load_factor()<<"\n";  
  cout<<"Max load factor = "<<uMap.max_load_factor();

  return 0;
}

The output of the above code will be:

Size = 3
Bucket count = 13
load factor = 0.230769
Max load factor = 1

max_load_factor is changed.

Size = 3
Bucket count = 13
load factor = 0.230769
Max load factor = 1.5

❮ C++ <unordered_map> Library