C++ unordered_map::hash_function() 函数



C++ 的std::unordered_map::hash_function() 函数用于计算 unordered_map 容器使用的哈希函数对象。哈希函数对象是类的实例,具有为给定元素生成唯一哈希值的功能。

哈希函数是一个一元函数,它接受类型为 key_type 的对象作为参数,并根据它返回类型为 size_t 的唯一值。

语法

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

hasher hash_function() 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

在以下示例中,我们演示了 hash_function() 的用法。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map <string, string> um; auto fun = um.hash_function(); cout << "Hash function for a = " << fun("a") << endl; cout << "Hash function for A = " << fun("A") << endl; return 0; }

输出

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

Hash function for a = 4993892634952068459
Hash function for A = 6919333181322027406

示例 2

考虑以下示例,我们将使用 hash_function() 获取指定字符串值的哈希值。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map <string, int> um; auto fun = um.hash_function(); cout << "Hash value of tutorialspoint = " << fun("tutorialspoint") << endl; cout << "Hash value of hyderabad = " << fun("hyderabad") << endl; return 0; }

输出

以下是上述代码的输出:

Hash value of tutorialspoint = 1837101086513568625
Hash value of hyderabad = 13759299188341863370

示例 3

让我们看一下以下示例,我们将创建一个 unordered_map 并计算每个键的哈希值。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map <string, int> um = {{"Aman", 1}, {"Vivek", 2}, {"Rahul", 3}}; auto fun = um.hash_function(); for(auto it = um.begin(); it!=um.end(); ++it){ cout << "Hash value of "<<it->first<<" "<<fun(it->first) << endl; } return 0; }

输出

上述代码的输出如下:

Hash value of Rahul 3776999528719996023
Hash value of Vivek 13786444838311805924
Hash value of Aman 17071648282880668303
广告