【发布时间】:2020-02-21 10:15:37
【问题描述】:
我有用于无序向量集的自定义散列函数:
struct VectorHash {
int operator()(const vector<int> &V) const {
int hsh=V[0] + V[1];
return hash<int>()(hsh);
}};
对于两个这样的向量,我有相同的哈希等于 3:
vector<int> v1{2,1};
vector<int> v2{1,2};
但是当我尝试在 unordered_set 中插入第一个向量 v1,然后通过哈希检查我是否在我的 unordered_set 中具有与 v2 相同的向量时,我得到了错误:
std::unordered_set<std::vector<int>, VectorHash> mySet;
mySet.insert(v1);
if(mySet.find(v2) == mySet.end())
cout << "didn't find" << endl;
Output: "didn't find"
我假设如果 unordered_set 中的两个元素具有相同的哈希值,那么如果我的 unordered_set 中有 v1,当我尝试查找 v2 时,find 方法应该返回 true。但事实并非如此。
谁能解释一下我的推理有什么问题?
【问题讨论】:
标签: c++ unordered-set