list容器对于自定义数据类型排序
要求:按照年龄排序,如果年龄相同,按照身高排序
#include<iostream>
#include<string>
#include<list>
using namespace std;
//list容器对于自定义数据类型排序
//按照年龄排序,如果年龄相同,按照身高排序
class Person {
public:
Person(string name, int age, int m_Height) {
this->age = age;
this->m_Height = m_Height;
this->name = name;
}
string name;
int age;
int m_Height;
};
//指定排序规则:
bool comparePerson(Person& p1, Person& p2) {
//按照年龄升序
if (p1.age == p2.age) {
//年龄相同,按照升高降序
return p1.m_Height > p2.m_Height;
}
return p1.age < p2.age;
}
void test01() {
list<Person>L;
Person p1("aaa", 35, 175);
Person p2("bbb", 40, 173);
Person p3("ccc", 20, 174);
Person p4("ddd", 18, 176);
Person p5("eee", 35, 177);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "姓名" << (*it).name << "年龄:" << (*it).age << "身高:" << (*it).m_Height << endl;
}
cout << "---------------------------------------" << endl;
//排序
L.sort(comparePerson);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "姓名" << (*it).name << "年龄:" << (*it).age << "身高:" << (*it).m_Height << endl;
}
}
int main() {
test01();
system("pause");
return 0;
}