C++ STL 为std::unordered_set提供自定义哈希函数
所有哈希表都使用一个哈希函数,该函数将放入容器的元素的值映射到特定的存储桶。目标两个是相等的值始终生成相同的存储桶索引,而对于不同的值,理想情况下应处理不同的存储桶条目。对于任何传递值的范围,哈希函数应提供哈希值的良好分布。
哈希函数必须是一个函数或函数对象,它以元素类型的值作为参数并返回std::size_t类型的值。因此,不考虑当前的存储桶数。将返回值映射到有效存储桶索引的范围是在容器内部完成的。因此,目标是提供一个函数,用于映射在[0, size_t]范围内均匀分布的不同元素值。
下面是一个自定义哈希函数的示例:
#include <iostream>
#include <unordered_set>
class Customer
{
//...;
};
class CustomerHash
{
public:
size_t operator() (const Customer& c) const
{
return 1; //...;
}
};
int main()
{
std::unordered_set<Customer, CustomerHash> custset;
getchar();
return 0;
}
此处,CustomerHash是一个函数对象,用于定义Customer类的哈希函数。
除了将函数对象传递给容器的类型之外,还可以传递哈希函数作为构造参数。但请注意,必须相应地设置哈希函数的模板类型:
std::size_t customer_hash_func(const Customer& c)
{
return ...
}
std::unordered_set<Customer, std::size_t(*)(const Customer&)> customer_set(20, customer_hash_func);
此处,customer_hash_func()作为第二个构造参数传递。
如果未传递哈希函数,则使用默认哈希函数 std::hash<>
,该函数在 <functional>
头文件中作为函数对象提供,用于常见类型:所有整数、所有浮点数、指针、字符串和一些特殊类型。对于其它类型,必须提供自己的哈希函数。
// 定义于头文件 <functional>
template<class Key>
struct hash;
template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<char8_t>; // C++20
template<> struct hash<char16_t>;
template<> struct hash<char32_t>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
template<> struct hash<unsigned short>;
template<> struct hash<int>;
template<> struct hash<unsigned int>;
template<> struct hash<long>;
template<> struct hash<long long>;
template<> struct hash<unsigned long>;
template<> struct hash<unsigned long long>;
template<> struct hash<float>;
template<> struct hash<double>;
template<> struct hash<long double>;
template<> struct hash<std::nullptr_t>;
template< class T > struct hash<T*>;
std::hash<std::string> (C++11)
std::hash<std::u8string> (C++20)
std::hash<std::u16string> (C&