C++ 无序集合中的散列函数

C++ 无序集合中的散列函数,c++,hashtable,unordered-set,C++,Hashtable,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 = hashed

我正在使用无序的_集实现一个哈希表。我不知道如何使用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;
}

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

我知道无法找到它应该包含的元素的根本原因

散列函数中是否使用staic变量。

将您的
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;
    }
};
for (int i = 0; i < 10; ++i) 
{
    got = hashedData.find(data[i]);
    if (got != hashedData.end())
    {
        cout<<(*got)->getSummary()<<endl;
    }
}
此函数有问题,当同一对象
A
调用此函数两次时,结果不同。因为您使用的是静态变量
static int hash=0。因此,在您构建
hashedData
时,函数
Hash
调用一次,当您使用
find
函数时,相同的对象再次调用
Hash
,但得到的结果不同,因此函数
find
返回
hashedData.end()

调用
cout getSummary()时
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;
    }
};
for (int i = 0; i < 10; ++i) 
{
    got = hashedData.find(data[i]);
    if (got != hashedData.end())
    {
        cout<<(*got)->getSummary()<<endl;
    }
}