I hope you help me to understand what's wrong with my code.
(希望您能帮助我了解我的代码有什么问题。)
Basically I need an unordered_set of tuples, but every time I call the insert function, I see that even when the hash is the same, the tuple is being inserted which means that I have tuples with the same hash in an unordered_set.
(基本上,我需要一个unordered_set的元组,但是每次调用insert函数时,我都会看到即使散列相同,也会插入该元组,这意味着我在unordered_set中具有具有相同散列的元组。)
To be more clear, let me share a piece of code here. (更清楚地说,让我在这里分享一段代码。)
So, this is how my example looks like:
(因此,我的示例如下所示:)
#include <iostream>
#include <tuple>
#include <unordered_set>
using namespace std;
using namespace testing;
struct MyHash {
size_t operator()(const tuple<int, int, int>& t) const
{
auto [num1, num2, num3] = t;
vector<int> v(3);
v[0] = num1;
v[1] = num2;
v[2] = num3;
sort(v.begin(), v.end());
string key = to_string(v[0]) + "|" + to_string(v[1]) + "|" + to_string(v[2]);
auto hashValue = hash<string>()(key);
cout << "Hash value for " << key << "= " << hashValue << endl;
return hashValue;
}
};
int main(int argc, char** argv)
{
unordered_set<tuple<int, int, int>, MyHash> s;
s.insert(make_tuple(1, 2, 3));
s.insert(make_tuple(1, 3, 2));
s.insert(make_tuple(3, 2, 1));
cout << "Amount of items = " << s.size() << endl;
}
and this is the output I got:
(这是我得到的输出:)
Hash value for 1|2|3= 12066275531359578498
Hash value for 1|2|3= 12066275531359578498
Hash value for 1|2|3= 12066275531359578498
Amount of items = 3
Why if the hash value for each entry is the same the amount of item inserted is 3?
(如果每个条目的哈希值相同,为什么插入的项数为3?)
I was expecting having only one. (我期待只有一个。)
Regards
(问候)
ask by Freddy Martinez Garcia translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…