C++ unordered_multimap::bucket() 函数



C++ 的std::unordered_multimap::bucket()函数用于返回包含键为k的元素所在的桶号。

桶是容器哈希表中的一个内存空间,元素根据其键的哈希值分配到该内存空间。桶的大小范围是0到bucket_count-1。

语法

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

size_type bucket(const Key& keyval) 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.

返回值

此函数返回无符号整型,表示对应于键的桶的序号。

示例 1

在以下示例中,让我们看看unordered_multimap::bucket()函数的使用方法。

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

输出

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

Unordered multi-map contains following elements
Element [e : 5] is in 1 bucket.
Element [d : 4] is in 0 bucket.
Element [c : 3] is in 4 bucket.
Element [b : 2] is in 3 bucket.
Element [a : 1] is in 2 bucket.

示例 2

让我们看下面的例子,我们将创建一个存储字符串值的unordered_multimap,并应用bucket()函数来统计彼此分配的桶的数量。

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

输出

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

Element [Akash : Daltonganj] is in 4 bucket.
Element [Vivek : Kanpur] is in 4 bucket.
Element [Vivek : Kanpur] is in 4 bucket.
Element [Aman : Ranchi] is in 3 bucket.
Element [Aman : Ranchi] is in 3 bucket.

示例 3

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

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

输出

以下是上述代码的输出:

The bucket number of key Akash is 4

示例 4

以下是一个示例,我们将显示当前unordered_multimap中指定键的桶号。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_multimap<char, int> umm = { {'A', 1}, {'B', 2}, {'C', 3}, {'A', 1}, {'D', 4}, {'A', 1}, {'E', 5}, {'D', 4}, }; cout<<umm.bucket('A')<<endl; cout<<umm.bucket('D')<<endl; return 0; }

输出

以上代码的输出如下:

10
2
广告