C++ Unordered_map 库 - bucket() 函数
描述
C++ 函数 std::unordered_map::bucket() 返回带有 k 键的元素所在的桶号。
Bucket 是容器哈希表中的一个内存空间,元素根据其键的哈希值分配到该内存空间。 桶的有效范围是从 0 到 bucket_count - 1。
声明
以下是 std::unordered_map::bucket() 函数形式 std::unordered_map 头的声明。
C++11
size_type bucket(const key_type& k) const;
参数
k − 要定位其存储桶的键。
返回值
返回key k对应的bucket的序号。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 std::unordered_map::bucket() 函数的用法。
#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.

