3.7.8 排序案例
案例描述:
- 将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高排序
- 规则:按照年龄进行升序,如果年龄相同按照身高进行降序
class Student
{
public:
Student(string name, int age,int height)
{
this->m_name = name;
this->m_age = age;
this->m_height = height;
}
string m_name;
int m_age;
int m_height;
};
//指定排序规则
bool Comp(Student &stu1, Student &stu2)
{
if (stu1.m_age == stu2.m_age)
{
return stu1.m_height > stu2.m_height;
}
else
{
return stu1.m_age < stu2.m_age;
}
}
list<Student> stu;
Student stu1("dwas",35,175);
Student stu2("das", 45, 180);
Student stu3("daas", 40, 170);
Student stu4("ddsas", 25, 190);
Student stu5("dadss", 35, 160);
Student stu6("dcsas", 35, 200);
stu.push_back(stu1);
stu.push_back(stu2);
stu.push_back(stu3);
stu.push_back(stu4);
stu.push_back(stu5);
stu.push_back(stu6);
for (list<Student>::iterator it = stu.begin(); it !=stu.end(); it++)
{
cout << (*it).m_name << " " << (*it).m_age << " " << (*it).m_height << endl;
}
cout << "--------------------" << endl;
stu.sort(Comp);
for (list<Student>::iterator it = stu.begin(); it != stu.end(); it++)
{
cout << (*it).m_name << " " << (*it).m_age << " " << (*it).m_height << endl;
}