[英]Hash function in an unordered_set
我正在使用unordered_set實現哈希表。 我不知道如何使用查找功能。 運行此代碼時,我始終遇到段錯誤。 我知道這是因為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
函數中使用staic variale嗎?
將您的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
,但是得到的結果不同,因此funtiocn find
返回hashedData.end()
。
當您調用cout << (*got)->getSummary() << endl << endl;
,您將遇到段錯誤。 您應該這樣做:
for (int i = 0; i < 10; ++i)
{
got = hashedData.find(data[i]);
if (got != hashedData.end())
{
cout<<(*got)->getSummary()<<endl;
}
}
嘗試將自己的Pred評估器添加為unordered_set的第三個參數。 然后,您可以檢查正在比較的兩個參數。 還要在查找調用之后確認您的迭代器不等於end()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.