C++ Unordered_map::hash_function() Function



The C++ std::unordered_map::hash_function() function is used to calculates the hash function object used by the unordered_map 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.

The hash function is a unary function that takes an object of type key_type as argument and returns a unique value of type size_t based on it.

Syntax

Following is the syntax of std::unordered_map::hash_function() function.

hasher hash_function() const;

Parameters

This function does not accepts any parameter.

Return value

This function returns a unique identifier or hash value of the specified argument.

Example 1

In the following example, we are demonstrating the usage of the hash_function().

#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;
}

Output

Let us compile and run the above program, this will produce the following result −

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

Example 2

Consider the following example, where we are going to use the hash_function() to get the hash value of the specified string value.

#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;
}

Output

Following is the output of the above code −

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

Example 3

Let's look at the following example, where we going to create an unordered_map and calculate the hash value of each key.

#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;
}

Output

Output of the above code is as follows −

Hash value of Rahul 3776999528719996023
Hash value of Vivek 13786444838311805924
Hash value of Aman 17071648282880668303
Advertisements