unordered map使用

1.基本数据类型,string等使用unordered map可以直接使用,如hash<int>()(x)。

结构体使用unordered map需要一个hash函数和一个equal函数。

2.

hash函数一般用函数对象实现。(注意:返回值size_t)

equal函数可以用函数对象,也可以直接重载==运算符。

struct point{
    int x,y;
}p;
unordered_map<point,vector<int>,pointHash ,pointEqual> mp;//equal用函数对象
unordered_map<point,vector<int>,pointHash> mp;//equal重载==

a.hash函数

比较朴素的方法就是直接相加。

struct pointHash{
    size_t operator () (const point &p) const{
        return hash<int>()(p.x) + hash<int>() (p.y);
    }
};

复杂一点就是。。

template<typename T>
inline void hash_combine(std::size_t& seed, const T& val)
{
    seed ^= std::hash<T>()(val)+0x9e3779b9 + (seed << 6) + (seed >> 2);
}

template<typename T>
inline void hash_val(std::size_t& seed, const T& val)
{
    hash_combine(seed, val);
}

template<typename T, typename... Types>
inline void hash_val(std::size_t& seed, const T& val, const Types&... args)
{
    hash_combine(seed, val);
    hash_val(seed, args...);
}

template<typename... Types>
inline std::size_t hash_val(const Types& ...args)
{
    std::size_t seed = 0;
    hash_val(seed, args...);
    return seed;
}
struct pointHash{
    size_t operator () (const point &p) const{
        return hash_val(p.x,p.y);
    }
};

b.equal函数

重载==运算符

struct point{
    int x,y;
    bool operator == (const point &b) const{
        return x == b.x && y == b.y;
    }
}p;

对象函数

struct pointEqual{
    bool operator () (const point &a,const point &b) const{
        return a.x == b.x && a.y == b.y;
    }
};

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值