c++ - 用户定义的无序映射哈希函数

标签 c++ hash unordered-map

我已经为 unrorderd_map 定义了自己的哈希函数。但是我无法使用查找功能在容器中进行搜索。我尝试在散列函数中使用打印语句进行调试,它生成的散列值与插入键/值时生成的散列值相同。如果有人能指出错误就太好了。我在 Windows 上使用 Eclipse IDE 并使用 -std=c++11 进行编译

typedef struct tree node;

struct tree
{
int id;
node *left;
node *right;
};

class OwnHash
{
public:
    std::size_t operator() (const node *c) const
    {
       cout << "Inside_OwnHash: " <<std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right) << endl;
       return std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right);
    }
};

int main()
{
std::unordered_map<node *,node *,OwnHash> ut;

node * one = new node;
one->id = -1;
one->left = nullptr;
one->right = nullptr;
ut.insert({one,one});

node * zero = new node;
zero->id = 0;
zero->left = NULL;
zero->right = NULL;
ut.insert({zero,zero});

node * cur = new node;
cur->id = 5;
cur->left = zero;
cur->right = one;
ut.insert({cur,cur});

for (auto& elem : ut)
{
    std::cout << "key: " << elem.first << "\t" << "value: " << elem.second->id << std::endl;
}

node * parse = new node;
parse->id = 5;
parse->left = zero;
parse->right = one;

std::unordered_map<node *,node *>::const_iterator got1 = ut.find (parse);

if ( got1 == ut.end() )
    std::cout << "not found";
else
    std::cout << got1->first << " is " << got1->second->id << std::endl;

return EXIT_SUCCESS;
}

    Output:
    Inside_OwnHash: 4294967295
    Inside_OwnHash: 0
    Inside_OwnHash: 22946517
    key: 0xaf11b0   value: 5
    key: 0xaf1180   value: 0
    key: 0xaf1150   value: -1
    Inside_OwnHash: 22946517
    not found

最佳答案

Hash 不够,还必须实现相等比较!

散列必须是一个函数,如果项目相等,则它们的散列值相等。但是由于项目可能是任意复杂的并且散列结果只是 size_t,因此相反的含义不成立也不能成立。因此,要找到确切的元素,您还需要进行相等比较。

查找时,hash函数将其指向正确的“桶”,但其中可能有多个元素,也可能有一个元素,但不是你要找的那个。因此它获取存储桶中的所有元素并将每个元素与您正在搜索的元素进行比较。

现在你提供了一个散列函数,但没有提供相等比较器。所以它使用默认值,即 operator== 并且用于定义为比较地址的指针。而且地址相等。您需要提供比较值的相等仿函数。

关于c++ - 用户定义的无序映射哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16118155/

相关文章:

c++ - 如何为无序容器中的用户定义类型专门化 std::hash<Key>::operator()?

c++ - 嵌套结构构造函数和 Union 的问题

c++ - 可变参数宏扩展

c - 是否可以制作一个对字典进行排序的哈希函数

c++ - unordered_map 迭代器比较中出现意外错误

c++ - 为什么我们没有 map 的 hash 和 pred 仿函数?

c++ - 二维数据点集的加权线性最小二乘法

c++ - 翻转卡片以获得最大金额

security - 密码哈希值的非随机盐

java - 使 Sim Hash(局部敏感哈希)算法更准确?