std::hash<Key>::operator()
来自cppreference.com
std::hash 的特化应定义满足下列条件的 operator():
- 接收单个
Key类型的实参key。 - 返回表示
key的散列值的std::size_t类型的值。 - 对于两个相等的参数
k1与k2,std::hash<Key>()(k1) == std::hash<Key>()(k2)。 - 对于两个不相等的不同参数
k1与k2,std::hash<Key>()(k1) == std::hash<Key>()(k2)的概率应该非常小,接近1.0/std::numeric_limits<size_t>::max()。
参数
| key | - | 要被散列的对象 |
返回值
表示散列值的 std::size_t。
异常
散列函数不应抛异常。
示例
下列代码演示如何为自定义类特化 std::hash 模板。此散列函数使用 Fowler–Noll–Vo 散列算法。
运行此代码
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
struct Employee
{
std::string name;
std::uint64_t ID;
};
namespace std
{
template <>
class hash<Employee>
{
public:
std::uint64_t operator()(const Employee& employee) const
{
// 用 Fowler-Noll-Vo hash 哈散列函数的变体计算 employee 的散列值
constexpr std::uint64_t prime{0x100000001B3};
std::uint64_t result{0xcbf29ce484222325};
for (std::uint64_t i{}, ie = employee.name.size(); i != ie; ++i)
result = (result * prime) ^ employee.name[i];
return result ^ (employee.ID << 1);
}
};
}
int main()
{
Employee employee;
employee.name = "Zaphod Beeblebrox";
employee.ID = 42;
std::hash<Employee> hash_fn;
std::cout << hash_fn(employee) << '\n';
}
输出:
12615575401975788567