在C++ STL中的unordered_map hash_function()函数
unordered_map::hash_function()是C++ STL中的内置函数,用于获取哈希函数。此哈希函数是一个一元函数,只接受一个参数,并根据它返回一个唯一的size_t类型值。
语法:
unordered_map_name.hash_function()
参数:该函数不接受任何参数。
返回值:该函数返回哈希函数。
时间复杂度:该函数的时间复杂度为O(1)。
下面的程序演示了unordered_map::hash_function()函数。
例子1
// C++ program to illustrate the
// unordered_map::hash_function()
#include <bits/stdc++.h>
using namespace std;
int main()
{
// declaration
unordered_map<string, string> sample;
// inserts key and elements
sample.insert({ "Ankit", "MNNIT" });
sample.insert({ "Ram", "MNNIT" });
sample.insert({ "Manoj", "Trichy" });
sample.insert({ "geeks", "geeks" });
// use of hash_function
unordered_map<string, string>::hasher fn
= sample.hash_function();
cout << fn("geeks") << endl;
// print the key and elements
cout << "Key and Elements: ";
for (auto it = sample.begin(); it != sample.end(); it++) {
cout << "\n{" << it->first << ":"
<< it->second << "}, ";
}
return 0;
}
15276750567035005396
Key and Elements:
{geeks:geeks},
{Manoj:Trichy},
{Ankit:MNNIT},
{Ram:MNNIT},
例子2
// C++ program to illustrate the
// unordered_map::hash_function()
#include <bits/stdc++.h>
using namespace std;
int main()
{
// declaration
unordered_map<int, int> sample;
// inserts key and elements
sample.insert({ 1, 5 });
sample.insert({ 2, 6 });
sample.insert({ 3, 6 });
sample.insert({ 4, 7 });
// use of hash_function
unordered_map<int, int>::hasher fn
= sample.hash_function();
cout << fn(4) << endl;
// print the key and elements
cout << "Key and Elements: ";
for (auto it = sample.begin(); it != sample.end(); it++) {
cout << "\n{" << it->first << ":"
<< it->second << "}, ";
}
return 0;
}
4
Key and Elements:
{4:7},
{3:6},
{1:5},
{2:6},