The C++ std::unordered_set::load_factor() function is used to return the load factor of the unordered_set container or the average number of element per bucket. The load factor is the ratio between the number of elements in the unordered_set and the number of buckets.
SyntaxThe load factor is calculated as follows −
load_factor = us.size() / us.bucket_count()The load factor will displays 0, if the unordered_set contains 0 elements.
Following is the syntax of std::unordered_set::load_factor() function.
float load_factor() const noexcept;Parameters
This function does not accepts any parameter.
Return ValueThis function returns the current load factor.
Example 1Consider the following example, where we are going to demonstrate the usage of unordered_set::load_factor() function.
#include <iostream> #include <unordered_set> using namespace std; int main () { unordered_set<int> uSet; cout << "size = " << uSet.size() << endl; cout << "bucket_count = " << uSet.bucket_count() << endl; cout << "load_factor = " << uSet.load_factor() << endl; //load_factor cout << "max_load_factor = " << uSet.max_load_factor() << endl; return 0; }Output
If we run the above code it will generate the following output −
size = 0 bucket_count = 1 load_factor = 0 max_load_factor = 1Example 2
In the following example, we are going to count the load_factor of the unordered_set.
#include <iostream> #include <unordered_set> using namespace std; int main () { unordered_set<int> uSet = {10, 20, 30, 40}; cout << "size = " << uSet.size() << endl; //Size of unordered set cout << "load_factor = " << uSet.load_factor() << endl; //load_factor return 0; }Output
Following is the output of the above code −
size = 4 load_factor = 0.307692Example 3
Let's look at the following example, where we are going to calculate the load_factor of the current unordered_set by using the formula.
#include <iostream> #include <unordered_set> using namespace std; int main () { unordered_set<int> uSet = {10, 20, 30, 40, 50}; float size = uSet.size(); float bucket_count = uSet.bucket_count(); cout << "size = " << size << endl; //Size of unordered set cout << "Bucket Count = " << bucket_count << endl; //Bucket count float load_factor = size/bucket_count; cout << "load_factor calculated by formula = " << load_factor << endl; //load_factor return 0; }Output
Output of the above code is as follows −
size = 5 Bucket Count = 13 load_factor calculated by formula = 0.384615
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4