目录

unordered_map::bucket

描述 (Description)

C ++函数std::unordered_map::bucket()返回带有键k的元素所在的桶号。

Bucket是容器哈希表中的一个内存空间,根据键的哈希值为其分配元素。 存储桶的有效范围是从0到bucket_count - 1

声明 (Declaration)

以下是std :: unordered_map :: bucket()函数形式std :: unordered_map头的声明。

C++11

size_type bucket(const key_type& k) const;

参数 (Parameters)

k - 要定位其存储桶的密钥。

返回值

返回与密钥k对应的桶的订货号。

时间复杂

常数即O(1)

例子 (Example)

以下示例显示了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.
↑回到顶部↑
WIKI教程 @2018