C++ unordered_map::bucket() 函数



C++ 函数unordered_map::bucket()函数返回键为k的元素所在的桶号。桶是容器哈希表中的一个内存空间,元素根据其键的哈希值分配到该空间。桶的有效范围是从 0 到bucket_count - 1.

语法

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

size_type bucket(const key_type& k) const;

参数

  • k − 表示要查找其桶的键。

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

返回值

返回无符号整型,表示对应于键k.

示例 1

在下面的示例中,我们将演示 unordered_map::bucket() 函数的用法。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void){ unordered_map<char, int> um = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5} }; for (auto it = um.begin(); it != um.end(); ++it) { cout << "Element " << "[" << it->first << " : "<< it->second << "] " << "is in "<< um.bucket(it->first) << " bucket." << endl; } return 0; }

输出

以下是上述代码的输出:

Element [e : 5] is in 3 bucket.
Element [d : 4] is in 2 bucket.
Element [c : 3] is in 1 bucket.
Element [b : 2] is in 0 bucket.
Element [a : 1] is in 6 bucket.

示例 2

在下面的示例中,我们创建一个只存储字符串值的 unordered_map,并计算当前 unordered_map 中分配给每个名称的桶数。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<string, string> um = { {"Aman", "Ranchi"}, {"Vivek", "Kanpur"}, {"Akash", "Daltonganj"}, {"Revathi", "Wrangle"}, {"Sarika", "Banaras"} }; for (auto it = um.begin(); it != um.end(); ++it) { cout << "Element " << "[" << it->first << " : " << it->second << "] " << "is in " << um.bucket(it->first) << " bucket." << endl; } return 0; }

输出

以下是上述代码的输出:

Element [Sarika : Banaras] is in 9 bucket.
Element [Revathi : Wrangle] is in 10 bucket.
Element [Akash : Daltonganj] is in 5 bucket.
Element [Vivek : Kanpur] is in 4 bucket.
Element [Aman : Ranchi] is in 8 bucket.

示例 3

考虑下面的示例,我们将显示从 unordered_map 中指向容器第一个元素的迭代器的桶数。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<string, string> um = { {"Aman", "Ranchi"}, {"Vivek", "Kanpur"}, {"Akash", "Daltonganj"}, {"Revathi", "Wrangle"}, {"Sarika", "Banaras"} }; // prints the bucket number of the beginning element auto it = um.begin(); // stores the bucket number of the key k int number = um.bucket(it->first); cout << "The bucket number of key " << it->first << " is " << number; return 0; }

输出

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

The bucket number of key Sarika is 9
广告