[英]Surprising behaviour with an unordered_set of pairs
如果(0, 1)
和(1, 0)
具有相同的 hash 值, unordered_set
如何能够同时保存它们?
#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;
}
Output:
0, 1, 1
1, 0, 1
2
1, 0
0, 1
unordered_set
可以保存任何唯一数据值的一个实例; 它不仅限于仅保存具有唯一哈希值的数据值。 特别是,当两个数据值不同(根据它们的==
运算符)但 hash 具有相同的哈希值时, unordered_set
将安排保存它们,不管怎样,通常效率会略有降低(因为任何哈希-基于对它们中的任何一个的查找将在内部 hash 到包含它们两者的数据结构,unordered_set 的查找代码将不得不对其进行迭代,直到找到它正在寻找的那个)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.