无序集合中的哈希函数

Hash function in an unordered_set

本文关键字:哈希 函数 集合 无序      更新时间:2023-10-16

我正在使用一个unordered_set来实现一个哈希表。我不知道如何使用find函数。当我运行这个代码时,我总是遇到seg错误。我知道它是因为find()没有找到元素,但它应该找到。我的问题是,如何将find与我提供的自定义哈希函数一起正确使用?

unordered_set<Play*, Play::Hash> hashedData
unordered_set<Play*>::iterator got;
for (int i = 0; i < 10; ++i) {
  got = hashedData.find(data[i]);
  cout << (*got)->getSummary() << endl << endl;
}

数据只是

vector<Play*>

我的散列函数看起来像这个

struct Hash {
    size_t operator()(Play* const &x) const {
      size_t t = 0;
      static int hash = 0;
      string u = x->getOffense();
      string v = x->getDefence();
      string w = x->getPlayDesc();
      t = u.length() + v.length() + w.length();
      t += hash;
      ++hash;
      return t;
    }
};

我知道为什么找不到应该找到的元素的根本原因。

您在Hash函数中使用了静态变量吗

Hash函数更改为如下:

struct Hash
{
    size_t operator()(Play* const &x) const 
    {
        size_t t = 0;
        string u = x->getOffense();
        string v = x->getDefence();
        string w = x->getPlayDesc();
        t = u.length() + v.length() + w.length();
        return t;
    }
};

此函数有问题,当同一对象A调用此函数两次时,结果不同。因为您使用了一个静态变量static int hash = 0;。因此,在您的情况下,当您构造hashedData时,函数Hash调用一次,当您使用find函数时,同一对象再次调用Hash,但您得到的结果不同,因此函数find返回hashedData.end()

当您调用cout << (*got)->getSummary() << endl << endl;时,您将遇到seg故障。你应该这样做:

for (int i = 0; i < 10; ++i) 
{
    got = hashedData.find(data[i]);
    if (got != hashedData.end())
    {
        cout<<(*got)->getSummary()<<endl;
    }
}

尝试将您自己的Pred计算器作为第三个参数添加到您的无序集合中。然后,您可以检查正在比较的两个参数。还要验证迭代器在调用find之后是否等于end()。