What is the unordered_map::load_factor() function in C++?

Overview

The unordered_map::load_factor() function is used to obtain the load factor of the unordered map.

It is available in the <unordered_map> header file in C++

Syntax

float load_factor();

Parameter

The unordered_map::load_factor() method does not take any parameters.

Return

The unordered_map::load_factor() returns the load factor of the unordered map.

Code

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, string> umap ={
{12, "unordered"},
{16, "map"},
{89, "in"},
{66, "C++"}
};
cout << "Current load factor of the map is : " << umap.load_factor() << endl;
cout<<"Buckets are: "<<umap.bucket_count()<<endl;
cout<<"Map size is: "<<umap.size()<<endl<<endl;
umap.insert({1,"load"});
umap.insert({34,"factor"});
cout<<"inserting {1,\"load\"}"<<endl;
cout<<"inserting {34,\"factor\"}"<<endl<<endl;
cout << "Current load factor of the map is : " << umap.load_factor() << endl;
cout<<"Buckets are: "<<umap.bucket_count()<<endl;
cout<<"Map size is: "<<umap.size()<<endl;
return 0;
}

Explanation

  • Lines 7 to 12: We initialize an unordered_map with integer type keys and string type values.

  • Line 15: We use the unordered_map::load_factor() method to obtain the current load factor of the map and display it.

  • Line 16: We use the unordered_map::bucket_count() to display the current number of buckets.

  • Line 17: We use the unordered_map::size() to display the current size of the map.

  • Lines 19 to 20: We add two more entries to the map.

  • Lines 26 to 28: We display load factor, bucket size, and map size, respectively.

Free Resources

Attributions:
  1. undefined by undefined