无法在 unordered_set 中找到 () 结构属性
unable to find() struct attribute inside unordered_set
我有以下代码用于向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"; });
但这将执行集合的线性搜索,而不是基于哈希的查找。
相关文章:
- C++概念:如何使用'concept'检查模板化结构的属性?
- "perf_event_attr"结构的"read_format"属性的选项到底是什么?
- 使用内存地址访问结构的属性值
- 通过指针算法调用结构的结构属性
- 无法在 unordered_set 中找到 () 结构属性
- 嵌套结构属性继承
- 在C++中循环数组时访问结构属性
- 为什么结构属性声明和初始化顺序的行为是这样的?
- gcc 显示结构属性为 0,但 clang 显示不同的值
- 使用 Spirit 将 std::vector<std::vector<double> 解析为结构属性
- 如何使用索引访问C 结构属性值
- 从外部函数访问外部结构属性
- 如何在C++中将结构属性转换为指针引用
- 如何通过字符串名称访问结构属性
- 提升灵气自定义句法属性(通过语义动作设置结构属性的特定成员)
- boost::spirit::qi具有相同的简单自适应结构属性的规则会导致编译错误
- 结构属性操作符重载
- 读取int*类型的结构属性值时遇到问题
- 模板递归中的函数、结构枚举和结构属性有什么区别?
- 在 C 中,除了使用 val 之外,不能更改结构属性 #define