What is the unordered_map::max_load_factor function in C++?
In this shot, we will learn how to use the unordered_map::max_load_factor function.
Introduction
The unordered_map::max_load_factor function is used to obtain or assign the maximum load factor to an unordered map.
Load factor is the ratio between the number of elements and the number of available buckets in the unordered map.
The unordered_map::max_load_factor function is available in the <unordered_map> header file in C++.
Syntax
The syntax of the unordered_map::max_load_factor function is given below:
float max_load_factor(); // used to get the maximum load factor
void max_load_factor(int size); // used to set the maximum load factor
Parameter
The first variation of the function, unordered_map::max_load_factor(), does not accept any parameter.
The second variation of the function, unordered_map::max_load_factor(int size), accepts one parameter: the maximum load factor that needs to be set for the unordered map.
Return
The first variation, unordered_map::max_load_factor(), returns the maximum load factor of the unordered map.
The second variation, unordered_map::max_load_factor(int size), does not return any value.
Code
Let’s have a look at the code now.
#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 << "Current maximum load factor of the map is " << umap.max_load_factor() << endl;umap.max_load_factor(2.67);cout << "Current maximum load factor of the map is " << umap.max_load_factor() << endl;return 0;}
Explanation
- In lines 1-2, we import the required header files.
- In line 5, we make a
mainfunction. - In lines 7-12, we initialize an unordered map with integer type keys and string type values.
- In line 14, we use
unordered_map::load_factor()to obtain the current load factor of the map and display it. - In line 16, we use
unordered_map::max_load_factor()to obtain the current maximum load factor of the map and display it. - In line 18, we use the
unordered_map::max_load_factor()function to reassign the maximum load factor of the map. - In line 20, we use the
unordered_map::max_load_factor()function again to obtain the current maximum load factor of the map and display it.
This is how we use the unordered_map::max_load_factor() function in C++.