C++ unordered_map::max_bucket_count() 函数



C++ 的std::unordered_map::max_bucket_count()函数用于返回unordered_map容器根据其当前内存分配可以容纳的最大桶数。unordered_map中的每个桶都是一个容器,用于保存具有相同哈希值的元素。

桶是容器内部哈希表中的一个槽,元素根据其键的哈希值分配到该槽中。容器中桶的实际数量始终小于max_bucket_count()函数返回的最大数量。

语法

以下是std::unordered_map::max_bucket_count()函数的语法。

size_type max_bucket_count() const;

参数

此函数不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回一个无符号整数,表示最大桶数。

示例 1

让我们看下面的例子,我们将创建一个包含零个元素的映射并应用max_bucket_count()并观察输出。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<char, int> um; cout << "max_bucket_count of unordered_map = " << um.max_bucket_count() << endl; return 0; }

输出

让我们编译并运行上述程序,这将产生以下结果:

max_bucket_count of unordered_map = 1152921504606846975

示例 2

在下面的示例中,我们将创建一个包含三个元素的映射并应用max_bucket_count()函数。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<char, int> um={{'A', 1}, {'B', 2}, {'C', 3}}; cout << "max_bucket_count of unordered_map = " << um.max_bucket_count() << endl; return 0; }

输出

如果我们运行上述代码,它将生成以下输出:

max_bucket_count of unordered_map = 576460752303423487

示例 3

以下是一个示例,我们使用存储负值的映射并应用mac_bucket_count()函数。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<int, char> um={{-1, 'a'}, {-2, 'b'}, {-3, 'c'}}; cout << "max_bucket_count of unordered_map = " << um.max_bucket_count() << endl; return 0; }

输出

以下是上述代码的输出:

max_bucket_count of unordered_map = 576460752303423487

示例 4

考虑以下示例,我们将考虑空映射并比较在将元素插入映射后最大桶数是否相等。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main() { unordered_map<char, int> uMap; cout << "Size is : " << uMap.size() << endl; cout << "Max bucket count is : " << uMap.max_bucket_count() << endl; // insert elements uMap.insert({ 'a', 10 }); uMap.insert({ 'b', 12 }); uMap.insert({ 'c', 13 }); uMap.insert({ 'd', 15 }); uMap.insert({ 'e', 20 }); cout << "Size is : " << uMap.size() << endl; cout << "Max bucket count is : " << uMap.max_bucket_count() << endl; return 0; }

输出

上述代码的输出如下:

Size is : 0
Max bucket count is : 576460752303423487
Size is : 5
Max bucket count is : 576460752303423487
广告