std::hash<Key>::operator()
From cppreference.com
Specializations of std::hash should define an operator() that:
- Takes a single argument
keyof typeKey. - Returns a value of type
std::size_tthat represents the hash value ofkey. - For two parameters
k1andk2that are equal,std::hash<Key>()(k1) == std::hash<Key>()(k2). - For two different parameters
k1andk2that are not equal, the probability thatstd::hash<Key>()(k1) == std::hash<Key>()(k2)should be very small, approaching1.0 / std::numeric_limits<size_t>::max().
Parameters
Return value
A std::size_t representing the hash value.
Exceptions
Hash functions should not throw exceptions.
Example
The following code shows how to specialize the std::hash template for a custom class. The hash function uses Fowler–Noll–Vo hash algorithm.
Run this code
#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
struct Employee
{
std::string name;
std::size_t ID;
};
static_assert([](auto... sz) { return ((sizeof(std::size_t) == sz) or ...); }(4, 8));
namespace std
{
template <>
class hash<Employee>
{
public:
static constexpr std::size_t operator()(const Employee& employee)
{
// Computes the hash of an employee using Fowler-Noll-Vo-1a hash function.
constexpr std::size_t prime{sizeof(size_t) < 8 ? 0x01000193 : 0x100000001b3};
std::size_t result{sizeof(size_t) < 8 ? 0x811c9dc5 : 0xcbf29ce484222325};
for (auto ch : employee.name)
result = (result ^ ch) * prime;
return result ^ (employee.ID << 1);
}
};
}
int main()
{
std::hash<Employee> hash_fn;
std::cout << std::hex << hash_fn(Employee{"Zaphod Beeblebrox", 42}) << '\n';
}
Output:
6fbb35ba06f7b013
