C++ STL中的unordered_map::max_load_factor是內置函數,用於獲取和設置unordered_map中的最大負載係數。負載係數是容器中元件數與鏟鬥數之間的比率。默認情況下,unordered_map max_load係數為1.0。語法:max_load_factor有兩種函數。
- float max_load_factor()
- void max_load_factor(float new_size)
返回類型:僅第一個版本返回max_load_factor。
參數:隻有第二個版本接受新的尺寸。
Note:
- 第一版返回最大負載係數。
- 第二個版本設置了新的負載係數。
例子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;
}
輸出:
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
例子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;
}
輸出:
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
複雜:O(1)。
相關用法
注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 unordered_map max_load_factor in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。