C++ Unordered_set::hash_function() Function
The C++ std::unordered_set::hash_function() is used to get the hash function object of the allocated elements, which is calculated by the hash function object used by the unordered_set container.
A hash function object is an instance of a class that has the functionality to generate a unique hash value for a given element. It is a unary function that accepts key_type objuects as argument and returns a unique value of type size_t based on it.
Syntax
Following is the syntax of std::unordered_set::hash_function().
hasher hash_function() const;
Parameters
This function does not accepts any parameter.
Return Value
This function returns the hash function.
Example 1
Consider the following example, where we are going to demonstrate the usage of std::unordered_set::hash_function() function.
#include <iostream>
#include <string>
#include <unordered_set>
typedef std::unordered_set<std::string> stringset;
int main () {
stringset uSet;
stringset::hasher fn = uSet.hash_function();
std::cout << "This contains: " << fn ("This") << std::endl;
std::cout << "That contains: " << fn ("That") << std::endl;
return 0;
}
Output
If we run the above code it will generate the following output −
This contains: 16508604031426688195 That contains: 12586652871572997328
Example 2
Let's look at the following example, where we are going to calculate the hash value of each element of the unordered_set.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(void) {
unordered_set <string> uSet = {"Aman", "Vivek", "Rahul"};
auto fun = uSet.hash_function();
for(auto it = uSet.begin(); it!=uSet.end(); ++it){
cout << "Hash value of "<<*it<<" "<<fun(*it) << endl;
}
return 0;
}
Output
Following is the output of the above code −
Hash value of Rahul 3776999528719996023 Hash value of Vivek 13786444838311805924 Hash value of Aman 17071648282880668303
Example 3
In the following example, we are going to calculate the hash value of each element of the unordered_set of type char.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(void) {
unordered_set <char> uSet = {'a', 'b', 'c'};
auto fun = uSet.hash_function();
for(auto it = uSet.begin(); it!=uSet.end(); ++it){
cout << "Hash value of "<<*it<<" "<<fun(*it) << endl;
}
return 0;
}
Output
Output of the above code is as follows −
Hash value of c 99 Hash value of b 98 Hash value of a 97