1. 场景说明
一个Person类,具有age和height属性,按照age降序排列;如果age相同,则按照height降序排列。
2. 代码实现
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Person
{
public:
Person(string name, int height, int age)
{
this->m_name = name;
this->m_height = height;
this->m_age = age;
}
string m_name;
int m_height;
int m_age;
};
void printList(list<Person>&L)
{
for(list<Person>::iterator it=L.begin(); it != L.end(); it ++)
{
cout << "name:" << it->m_name << ", height:" << it->m_height << ", age:" << it->m_age << endl;
}
}
class Compare
{
public:
bool operator()(Person &p1, Person &p2)
{
if(p1.m_age == p2.m_age)
{
return p1.m_height > p1.m_height;
}
else
{
return p1.m_age > p2.m_age;
}
}
};
int main()
{
list<Person>L;
Person p1("guopei", 175, 30);
Person p2("guofan", 170, 28);
Person p3("guorong", 170, 32);
Person p4("caige", 160, 28);
Person p5("caipei", 170, 30);
Person p6("huqiang", 170, 32);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);
printList(L);
cout << "-----------------------------" << endl;
L.sort(Compare());
printList(L);
return 0;
}