C++ 在无序_集中找不到()结构属性
我有以下代码用于向无序的集合添加结构。现在我想搜索一个学生的名字是否已经在无序集合中。我该怎么做?当我创建一个键时,我需要传递三个参数,但我只想搜索第一个参数,即名称。如果我只为第一个参数创建一个键,我会得到一个错误C++ 在无序_集中找不到()结构属性,c++,stl,C++,Stl,我有以下代码用于向无序的集合添加结构。现在我想搜索一个学生的名字是否已经在无序集合中。我该怎么做?当我创建一个键时,我需要传递三个参数,但我只想搜索第一个参数,即名称。如果我只为第一个参数创建一个键,我会得到一个错误 #include <iostream> #include <unordered_set> using namespace std; struct Person { string name, biology; int scoreBio;
#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;
}
#包括
#包括
使用名称空间std;
结构人{
字符串名称,生物学;
int scoreBio;
//参数构造函数
人物(字符串pName、字符串pBiology、int pscoreBio)
{
name=pName;
生物学=生物学;
scoreBio=pscoreBio;
}
布尔运算符==(常数人和h)常数
{
返回name==h.name&&biology==h.biology&&scoreBio==h.scoreBio;
}
};
类MyHashFunction{
公众:
//我们使用预先定义的字符串哈希函数
//并将散列函数定义为
//散列值。
大小运算符()(const Person&h)const
{
返回(hash()(h.name))^(hash()(h.biology))^(hash()(h.scoreBio));
}
};
int main()
{
无序的学生;
p1人(“毛罗”,“生物学”,56岁);
p2人(“拉姆”、“辛格”,67岁);
p3人(“卡提克”、“卡普尔”,56岁);
学生。插入(p1);
学生。插入(p2);
学生。插入(p3);
人员密钥(“Mauro”,0);
if(Student.find(key)==Student.end())
cout无序集合中的find
函数搜索集合中的键。它查找与Person
的匹配项,因为这是映射中键的类型。映射中没有值为{“Mauro”,“0}的Person
s,因此find
调用返回end()
成员find
调用中没有搜索部分密钥的规定
您可以在此处使用自由算法find
和自定义谓词:
std::find(Student.begin(), Student.end(),
[] (const Person &p) { return p.name == "Mauro"; });
但这将对集合执行线性搜索,而不是基于散列的查找。也许无序映射
/无序多映射
(其中名称
是关键)会更好?可能的重复:这取决于您希望如何执行。