The unordered_map::max_load_factor in C++ STL is a built in function which is used to get and set maximum load factor in unordered_map. Load factor is the ratio between number of elements in container and number of buckets. By default unordered_map max_load factor is 1.0.
Syntax: There are two type of functions for max_load_factor.
- float max_load_factor()
- void max_load_factor(float new_size)
Return type: Only first version returns max_load_factor.
Parameter: Only second version accept new size.
Note:
- First version return maximum load factor.
- Second version sets new load factor.
Example 1
// C++ program to illustrate the // unordered_map::max_bucket_count function #include <bits/stdc++.h> using namespace std;
int main()
{ // declaration of unordered_map
unordered_map< char , int > sample;
// insert elements
sample.insert({ 'a' , 10 });
sample.insert({ 'b' , 10 });
sample.insert({ 'c' , 10 });
sample.insert({ 'd' , 10 });
sample.insert({ 'e' , 10 });
sample.insert({ 'f' , 10 });
cout << "Current size is : " << sample.size() << endl;
cout << "Current load factor is : " << sample.load_factor() << endl;
cout << "Current Max load factor is " << sample.max_load_factor() << endl;
// Changing max load factor
sample.max_load_factor(5.0 / 2.0);
cout << "Current size is : " << sample.size() << endl;
cout << "Current load factor is : " << sample.load_factor() << endl;
cout << "Current Max load factor is " << sample.max_load_factor() << endl;
return 0;
} |
Output:
Current size is : 6 Current load factor is : 0.857143 Current Max load factor is 1 Current size is : 6 Current load factor is : 0.857143 Current Max load factor is 2.5
Example 2
// C++ program to illustrate the // unordered_map::max_bucket_count function #include <bits/stdc++.h> using namespace std;
int main()
{ // declaration of unordered_map
unordered_map< int , int > sample;
// insert elements
sample.insert({ 1, 10 });
sample.insert({ 2, 10 });
sample.insert({ 3, 10 });
sample.insert({ 4, 10 });
cout << " Current size is : " << sample.size() << endl;
cout << " Current load factor is : " << sample.load_factor() << endl;
cout << " Current Max load factor is " << sample.max_load_factor() << endl;
// Changing max load factor
sample.max_load_factor(5.0 / 2.0);
cout << " Current size is : " << sample.size() << endl;
cout << " Current load factor is : " << sample.load_factor() << endl;
cout << " Current Max load factor is " << sample.max_load_factor() << endl;
return 0;
} |
Output:
Current size is : 4 Current load factor is : 0.571429 Current Max load factor is 1 Current size is : 4 Current load factor is : 0.571429 Current Max load factor is 2.5
Complexity : O(1).