微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 unordered_set 对的令人惊讶的行为

如何解决使用 unordered_set 对的令人惊讶的行为

如果 unordered_set(0,1) 具有相同的哈希值,它们如何能同时保存?

(1,0)

输出

#include <iostream>
#include <unordered_set>
#include <utility>

using namespace std;

struct PairHash
{
    template <class T1,class T2>
    size_t operator()(pair<T1,T2> const &p) const
    {
        size_t hash_first = hash<T1>{}(p.first);
        size_t hash_second = hash<T2>{}(p.second);
        size_t hash_combined = hash_first ^ hash_second;
        
        cout << hash_first << "," << hash_second << "," << hash_combined << endl;
        
        return hash_combined;    
    }
};

int main()
{
    unordered_set<pair<int,int>,PairHash> map;
    map.insert({0,1});
    map.insert({1,0});
    
    cout << map.size() << endl;

    for (auto& entry : map) {
        cout << entry.first << "," << entry.second << endl;
    }

    return 0;
}

Link to onlinegdb

解决方法

unordered_set 可以保存任何唯一数据值的一个实例;它不仅限于仅保存具有唯一哈希值的数据值。特别是,当两个数据值不同(根据它们的 == 运算符)但都散列到相同的散列值时,unordered_set 会做出安排来保存它们,通常在一个效率略有降低(因为任何基于散列的查找都会在内部散列到一个包含它们两个的数据结构,unordered_set 的查找代码必须迭代它,直到找到它正在寻找的那个)>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。