#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;
}
}
};
// 定义比较函数
bool compareName(const pair<Student, int>& p, const string& name)
{
return p.first.name == name;
}
bool compareId(const pair<Student, int>& p, const string& id)
{
return p.first.id == id;
}
bool compareAge(const pair<Student, int>& p, const int& age)
{
return p.first.age == age;
}
int main()
{
map<Student, int>m;
// 在map中添加元素
Student s1 = { "Tom", "001", 20 };
Student s2 = { "Jack", "002", 22 };
Student s3 = { "Lucy", "003", 21 };
m[s1] = 100;
m[s2] = 90;
m[s3] = 80;
// 根据名字查找
string name = "Jack";
auto it1 = find_if(m.begin(), m.end(), [&](const pair<Student, int>& p) {return compareName(p, name); });
if (it1 != m.end())
{
cout << "找到了,名字为" << it1->first.name << ",成绩为" << it1->second << endl;
}
else
{
cout << "未找到" << endl;
}
// 根据id查找
string id = "002";
auto it2 = find_if(m.begin(), m.end(), [&](const pair<Student, int>& p) {return compareId(p, id); });
if (it2 != m.end())
{
cout << "找到了,id为" << it2->first.id << ",成绩为" << it2->second << endl;
}
else
{
cout << "未找到" << endl;
}
// 根据年龄查找
int age = 21;
auto it3 = find_if(m.begin(), m.end(), [&](const pair<Student, int>& p) {return compareAge(p, age); });
if (it3 != m.end())
{
cout << "找到了,年龄为" << it3->first.age << ",成绩为" << it3->second << endl;
}
else
{
cout << "未找到" << endl;
}
return 0;
}