为什么在下面的哈希函数(它返回常量0)似乎没有任何效果?
由于哈希函数返回常数,所以我期望输出的所有值都为3,但是,似乎将std :: vector值唯一映射到唯一的值,而不管我的哈希函数是不变的.
#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
// Hash returning always zero.
class TVectorHash {
public:
std::size_t operator()(const std::vector<int> &p) const {
return 0;
}
};
int main ()
{
std::unordered_map<std::vector<int>,int,TVectorHash> table;
std::vector<int> value1({0,1});
std::vector<int> value2({1,0});
std::vector<int> value3({1,1});
table[value1]=1;
table[value2]=2;
table[value3]=3;
std::cout << "\n1=" << table[value1];
std::cout << "\n2=" << table[value2];
std::cout << "\n3=" << table[value3];
return 0;
}
获得的输出:
1=1 2=2 3=3
预期产量:
1=3 2=3 3=3
我缺少什么哈希?
解决方法
你误解了使用哈希函数:它不用于比较元素.在内部,地图将元素组织成桶,散列函数用于确定元素所在的桶.使用另一个模板参数执行元素的比较,查看unordered_map模板的完整声明:
template<
class Key,class T,class Hash = std::hash<Key>,class KeyEqual = std::equal_to<Key>,class Allocator = std::allocator< std::pair<const Key,T> >
> class unordered_map;
后面的模板参数是hasher后的关键比较器.要获得您期望的行为,您必须执行以下操作:
class TVectorEquals {
public:
bool operator()(const std::vector<int>& lhs,const std::vector<int>& rhs) const {
return true;
}
};
std::unordered_map<std::vector<int>,TVectorHash,TVectorEquals> table;
现在你的地图将有一个单一的元素,所有的结果将是3.