重载unordered_map与unordered_set中的hash函数

当C++编程中遇到需要使用hash_set或hash_map处理复杂类型的key时,如数对或自定义结构体,需要自定义hash函数。文章介绍了如何重载hash函数以确保正确性,并给出一个针对pair<int, int>的hashfun结构体实例,用于创建一个unordered_set。
摘要由CSDN通过智能技术生成

在编程的过程中,hash_set和hash_map的key有时候可能需要是一些复杂的元素,如数对,结构体或者某一个类,这时候可能需要自己重新写一个hash函数来使得hash_set和hash_map能够正常使用。hash_set和hash_map的结构如下,只需要重载除key和value的下一个参数即可。

template<class Key,
    class Ty,
    class Hash = std::hash<Key>,
    class Pred = std::equal_to<Key>,
    class Alloc = std::allocator<std::pair<const Key, Ty> > >
    class unordered_map;
    > class unordered_map

template<class value,
    class Hash = std::hash<value>,
    class Pred = std::equal_to<value>,
    class Alloc = std::alloc>
    class unordered_set;

重写hashfun结构体的内容如下:要注意hash<int>()(a.first)这个格式。

struct hashfun{
        size_t operator()(const pair<int,int>& a)const
        {
            return hash<int>()(a.first)*10+hash<int>()(a.second);
        }
    };

unordered_set<pair<int,int>,hashfun> check;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yanzhe1

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

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

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

打赏作者

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

抵扣说明:

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

余额充值