无法在 unordered_set 中找到 () 结构属性

unable to find() struct attribute inside unordered_set

本文关键字:结构 属性 unordered set      更新时间:2023-10-16

我有以下代码用于向unordered_set添加结构。现在我想搜索学生的名字是否已经在unordered_set中。我该怎么做?当我创建一个密钥时,我需要传递三个参数,但我只想搜索第一个参数,即名称。如果我只为第一个参数创建一个键,我得到一个错误。

#include <iostream> 
#include <unordered_set>
using namespace std;
struct Person {
string name, biology;
int scoreBio;
//param constructor
Person(string pName, string pBiology, int pscoreBio)
{
name = pName;
biology = pBiology;
scoreBio = pscoreBio;
}
bool operator==(const Person& h) const
{
return name == h.name && biology == h.biology && scoreBio == h.scoreBio;
}
};
class MyHashFunction {
public:
// We use predfined hash functions of strings 
// and define our hash function as XOR of the 
// hash values. 
size_t operator()(const Person& h) const
{
return (hash<string>()(h.name)) ^ (hash<string>()(h.biology)) ^ (hash<int>()(h.scoreBio));
}
};

int main()
{
unordered_set<Person, MyHashFunction> Student;
Person p1("Mauro", "Biology", 56);
Person p2("Ram", "Singh", 67);
Person p3("kartik", "kapoor", 56);


Student.insert(p1);
Student.insert(p2);
Student.insert(p3);
Person key("Mauro", "   ", 0);

if (Student.find(key) == Student.end())
cout << " not found" << endl << endl;
else
cout << "Found " << endl << endl;
for (auto e : Student) {
cout << e.name << " " << e.biology << " " << e.scoreBio << endl;
}
return 0;
}

unordered_set中的find函数搜索集合中的键。它寻找与Person的匹配,因为这是地图中键的类型。映射中没有值为 { "Mauro", " ", 0 } 的Person,因此find调用返回end()

成员find调用中没有用于搜索部分密钥的规定。

您可以在此处将免费算法find与自定义谓词一起使用:

std::find(Student.begin(), Student.end(), 
[] (const Person &p) { return p.name == "Mauro"; });

但这将执行集合的线性搜索,而不是基于哈希的查找。