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

User defined hash function for unordered map

本文关键字:哈希 函数 映射 定义 无序 用户      更新时间:2023-10-16

我已经为一个unorderd_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

哈希是不够的,你还必须实现相等比较!

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

查找时,哈希函数指向正确的"桶",但其中可能有多个元素,或者其中可能有一个元素,但不是您要查找的那个。因此,它获取bucket中的所有元素,并将每个元素与您正在搜索的元素进行比较。

现在您提供了一个散列函数,但没有提供相等比较器。所以它使用默认值,也就是operator==,那是用来比较地址的指针。地址不等于。您需要提供相等函子来比较值