📜  C++ STL中的unordered_map max_load_factor

📅  最后修改于: 2021-05-30 15:01:43             🧑  作者: Mango

C++ STL中的unordered_map :: max_load_factor是一个内置函数,用于获取和设置unordered_map中的最大负载因子。负载系数是容器中元件数与铲斗数之间的比率。默认情况下,unordered_map max_load系数为1.0。
语法: max_load_factor有两种类型的函数。

返回类型:仅第一个版本返回max_load_factor。

参数:仅第二个版本接受新的大小。

笔记:

  • 第一版返回最大负载系数。
  • 第二个版本设置了新的负载系数。

例子1

// C++ program to illustrate the
// unordered_map::max_bucket_count function
#include 
using namespace std;
  
int main()
{
  
    // declaration of unordered_map
    unordered_map 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 
using namespace std;
  
int main()
{
  
    // declaration of unordered_map
    unordered_map 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)。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”