unordered_map - 哈希函数不起作用

unordered_map - Hash function has no effect

本文关键字:函数 不起作用 哈希 map unordered      更新时间:2023-10-16

为什么在下面的哈希函数(返回常量 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;

哈希器之后的下一个模板参数是密钥比较器。要获得预期的行为,您必须执行以下操作:

class TVectorEquals {
public:
    bool operator()(const std::vector<int>& lhs, const std::vector<int>& rhs) const {
        return true;
    }
};
std::unordered_map<std::vector<int> ,int, TVectorHash, TVectorEquals> table;

现在,您的地图将具有单个元素,并且所有结果都将3

一个健全的哈希表实现不应该丢失信息,即使存在哈希冲突。有几种技术可以解决冲突(通常在运行时性能与数据完整性之间进行权衡)。显然,std::unordered_map实现了它。

请参阅: 哈希冲突解决方案

添加一个谓词键比较器类。

class TComparer {
public:
    bool operator()(const std::vector<int> &a, const std::vector<int> &b) const {
        return true; // this means that all keys are considered equal
    }
};

像这样使用它:

std::unordered_map<std::vector<int> ,int, TVectorHash, TComparer> table;

然后,其余代码将按预期工作。