pair作为unordered_map的key报错

问题

pair作为unordered_map的key报错,编译时会报错

原因

因为pair没有哈希函数

解决方法

定义哈希函数

cpp 复制代码
template <typename T>
inline void hash_combine(std::size_t &seed, const T &val) {
    seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// auxiliary generic functions to create a hash value using a seed
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 pair_hash {
    template <class T1, class T2>
    std::size_t operator()(const std::pair<T1, T2> &p) const {
        return hash_val(p.first, p.second);
    }
};

使用

cpp 复制代码
unordered_map<pair<long long, long long>, long long, pair_hash> slopeCount;
相关推荐
努力的小帅1 天前
C++_哈希
开发语言·c++·学习·算法·哈希算法·散列表
叙白冲冲2 天前
哈希算法以及面试答法
算法·面试·哈希算法
金古圣人3 天前
hot100 滑动窗口
数据结构·c++·算法·leetcode·哈希算法
YuTaoShao3 天前
【LeetCode 热题 100】49. 字母异位词分组
算法·leetcode·哈希算法
superlls3 天前
(数据结构)哈希碰撞:线性探测法 vs 拉链法
算法·哈希算法·散列表
酷ku的森4 天前
Redis中的hash数据类型
数据库·redis·哈希算法
闪电麦坤956 天前
数据结构:哈希(Hashing)
数据结构·算法·哈希算法
一起努力啊~6 天前
算法题打卡力扣第3题:无重复字符的最长子串(mid)
算法·leetcode·哈希算法
{⌐■_■}6 天前
【JavaScript】前端两种路由模式,Hash路由,History 路由
前端·javascript·哈希算法
野犬寒鸦7 天前
力扣hot100:缺失的第一个正数(哈希思想)(41)
java·数据结构·后端·算法·leetcode·哈希算法