hash Function Class in C++ STL
Last Updated :
03 Dec, 2024
In C++, the hash class is default constructible function class (functor) that provides the default hash function used by STL. It is used to get the hash value of the argument that is being passed to it. If the argument doesn't change, the value doesn't change either.
Let’s take a quick look at an example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "geeksforgeeks";
hash<string> h;
// Get the hash value of character
cout << h(s);
return 0;
}
Output5146686323530302118
Explanation: In the above code, first we generate the hash value of the string s by using hash class.
Note: The hash class is used by many different containers of C++ for determining hash values.
This article covers the syntax, usage, and common examples of hash class method in C++:
Syntax of hash Function Class
The hash function class is defined as std::hash class template in <functional> header file.
hash<T> h; // Create hash function for type T
h(val); // Generate the hash value
where, h is the name of object by which we can access the member function of hash class.
Parameters:
- val: Data whose hash value to be generate.
- T: Type of val.
Return Value:
- Returns a hash value of given arguments.
Examples of hash Function Class
The following examples demonstrates the use of hash class in different scenarios:
Generate the Hash Value of Bitset
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
bitset<5> b("10101");
// Create an object of hash class
hash<bitset<5>> h;
// Generate the hash value of given bitset
cout << h(b);
return 0;
}
Output17123654466142159564
Generate the Hash Value of Vector
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<bool> v = {true, false};
// Create an object of hash class
hash<vector<bool>> h;
// Generate the hash value of given vector
cout << h(v) << endl;
return 0;
}
Output4334672815104069193
Generate the Hash Value of Custom Data Type
To generate hash value for custom data type, a hash function for that type has to be defined manually. It can be done by specializing the hash class template to the given data type.
C++
#include <bits/stdc++.h>
using namespace std;
struct A {
int a;
A(int x = 0): a(x) {}
};
// Specialization of hash for A type
namespace std {
template <>
struct hash<A> {
size_t operator()(const A& p) const {
return hash<int>{}(p.a);
}
};
}
int main() {
A obj(11);
// Creating hash function class instance for
// A type
hash<A> h;
cout << h(obj);
return 0;
}