加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:27:17 所属栏目:百科 来源:网络整理
导读:为什么在下面的哈希函数(它返回常量0)似乎没有任何效果? 由于哈希函数返回常数,所以我期望输出的所有值都为3,但是,似乎将std :: vector值唯一映射到唯一的值,而不管我的哈希函数是不变的. #include iostream#include map#include unordered_map#include vec
为什么在下面的哈希函数(它返回常量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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读