2013-11-26 63 views
0

我正在使用unordered_set來實現散列表。我無法弄清楚如何使用find函數。運行此代碼時,我不斷收到seg錯誤。我知道它是因爲find()沒有找到一個元素,但它應該。我的問題是我如何正確使用我提供的自定義散列函數的查找?unordered_set中的散列函數

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; 
    } 
}; 

回答

1

我知道你爲什麼找不到它應該的元素的根本原因。

您是否在您使用staic variales 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,但是你得到的結果不一樣,所以funtiocn 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; 
    } 
} 
0

嘗試加入自己的強的鬆評估作爲第三個參數你unordered_set。然後你可以檢查兩個正在比較的參數。在調用查找之後,還要驗證你的迭代器不等於end()。