c – unordered_map – 哈希函数没有影响

c – unordered_map – 哈希函数没有影响,第1张

概述为什么在下面的哈希函数(它返回常量0)似乎没有任何效果? 由于哈希函数返回常数,所以我期望输出的所有值都为3,但是,似乎将std :: vector值唯一映射到唯一的值,而不管我的哈希函数是不变的. #include <iostream>#include <map>#include <unordered_map>#include <vector>// Hash returning al 为什么在下面的哈希函数(它返回常量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=12=23=3

预期产量:

1=32=33=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.

总结

以上是内存溢出为你收集整理的c – unordered_map – 哈希函数没有影响全部内容,希望文章能够帮你解决c – unordered_map – 哈希函数没有影响所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1247201.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存