16.7.5【列表list容器的排序案例】
#include<iostream> #include<cstdlib> using namespace std; #include<list> #include<string> /* 3.7.8 list容器的排序案例 案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高 排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序 */ class Person { public: string name; int age; int hight; public: Person(string _name, int _age, int _hight) { this->name = _name; this->age = _age; this->hight = _hight; } }; void print_info(const list<Person> & L) { for(list<Person>::const_iterator cit=L.begin(); cit!=L.end(); cit++) { cout << "name:" << (*cit).name << " age:" << cit->age << " hight:" << (*cit).hight << endl; //.和->都可以使用 } } bool compare_person(Person p1, Person p2) { if(p1.age == p2.age) { //身高降序:令 前一人身高 > 后一人身高 return p1.hight > p2.hight; } //年龄升序:令 前一人年龄 < 后一人年龄 return p1.age < p2.age; } void test378() { list<Person> L; Person p1("sam", 20, 180); Person p2("jack", 25, 178); Person p3("amy", 18, 166); Person p4("tom", 20, 175); Person p5("anne", 20, 200); L.push_back(p1); L.push_back(p2); L.push_back(p3); L.push_back(p4); L.push_back(p5); cout << "排序前:" << endl; print_info(L); L.sort(compare_person); //利用回调函数或仿函数自定义排序时的比较规则(此处为回调函数) cout << "排序后:" << endl; print_info(L); } int main() { test378(); //对于自定义数据类型,必须要指定排序规则,否则编译器不知道如何进行排序 //高级排序只是在排序规则上再进行一次逻辑规则制定,并不复杂 system("pause"); return 0; }