#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
class Student
{
public:
string name;
string id;
int age;
bool operator()(const Student& s1, const Student& s2)
{
if (s1.name == s2.name)
{
if (s1.id == s2.id)
{
return s1.age > s2.age;
}
else
{
return s1.id > s2.id;
}
}
else
{
return s1.name > s2.name;
}
}
// 新增函数,根据给出的关键字返回对应的Student对象
Student getByKey(string key) const {
Student s;
if (key == "name") {
s.name = this->name;
s.id = "";
s.age = 0;
} else if (key == "id") {
s.name = "";
s.id = this->id;
s.age = 0;
} else if (key == "age") {
s.name = "";
s.id = "";
s.age = this->age;
}
return s;
}
};
int main()
{
map<Student, int>m;
Student s1 = {"Tom", "001", 18};
m[s1] = 100;
// 根据name查找
Student s2 = s1.getByKey("name");
auto it = m.find(s2);
if (it != m.end()) {
cout << "Found, value is " << it->second << endl;
} else {
cout << "Not found" << endl;
}
// 根据id查找
Student s3 = s1.getByKey("id");
it = m.find(s3);
if (it != m.end()) {
cout << "Found, value is " << it->second << endl;
} else {
cout << "Not found" << endl;
}
// 根据age查找
Student s4 = s1.getByKey("age");
it = m.find(s4);
if (it != m.end()) {
cout << "Found, value is " << it->second << endl;
} else {
cout << "Not found" << endl;
}
return 0;
}
假如map类m的key值是一个Student类,现在已经重载比较运算符了,如果给出name或者id或者age进行查找,为什么这段代码报错?