2013-11-26 43 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()。