C++ 无序集合中的散列函数
我正在使用无序的_集实现一个哈希表。我不知道如何使用find函数。当我运行这个代码时,我总是遇到seg错误。我知道这是因为find()没有找到元素,但它应该找到。我的问题是如何正确使用find和我提供的自定义哈希函数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
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;
}
}