C++ STL 为std::unordered_set提供自定义哈希函数

本文介绍了如何为C++STL中的std::unordered_set提供自定义的哈希函数,以确保不同元素值能够正确映射到不同的存储桶。通过示例展示了如何创建哈希函数对象和使用函数指针,以及如何利用Boost库中的hash_combine函数来实现更高效的哈希函数。同时,文章强调了提供良好的哈希函数的重要性,并给出了使用lambda表达式定义哈希和等价标准的例子。
摘要由CSDN通过智能技术生成

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&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值