C++ Unordered_map::load_factor() Function



The C++ function std::unordered_map::load_factor() is used to return the load factor of the unordered_map or container. If the unordered map has 0 elements, then the load factor is 0. The load factor is the ratio between the number of elements in the unordered map and the number of buckets.

In this API, we are calculating the load factor of the container directly by using the std::unordered_map::load_factor() function, hence there is no need to calculate the ratio between the number of elements and the number of buckets.

The load factor is calculated as follows −

load_factor = um.size() / um.bucket_count()

Syntax

Following is the syntax of std::unordered_map::load_factor() function.

float load_factor() const noexcept;

Parameters

This function does not accepts any parameter.

Return value

This function returns the calculated load factor of the unordered_map or container.

Example 1

In the following example, we are calculating the load factor of the unordered map by using load_factor() function.

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um={{'A', 2}, {'B', 4}, {'C', 6}};
   cout << "load_factor of unordered_map = " << um.load_factor() << endl;
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

load_factor of unordered_map = 0.230769

Example 2

Following is the example, where we going to create a map that accepts string and integer type value and applying the load_factor() function to calculate the load factor of the current map.

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<int, string> um;
   um[2]="john";
   um[4]="garav";
   um[3]="rakesh";
   cout << "load_factor of unordered_map = " << um.load_factor() << endl;
   return 0;
}

Output

Following is the output of the above code −

load_factor of unordered_map = 0.230769

Example 3

Let's look at the following example, where we are going to calculate the load factore using to different methods one is with ratio between the size of the container and the number of buckets and other using the load_factor() function.

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<int, int> um;
   cout<<"Size of map "<<um.size()<<endl;
   cout<<"Size of bucket "<<um.bucket_count()<<endl;
   unsigned l_factor = um.size()/um.bucket_count();
   cout << "load_factor of unordered_map = " << l_factor << endl;
   cout << "load_factor of unordered_map = " << um.load_factor() << endl;
   return 0;
}

Output

Output of the above code is as follows −

Size of map 0
Size of bucket 1
load_factor of unordered_map = 0
load_factor of unordered_map = 0
Advertisements