需求;有一個類,類中有姓名和年齡成員變量,現在要按姓名升序排序,在姓名相同時按名字升序排序。
#include<iostream> #include<list> #include<algorithm> using namespace std; //加入const限制只讀,並使用const_iterator class Person { public: Person(string name, int age) { this->name = name; this->age = age; } string name; int age; }; //重載左移運算符 ostream& operator<<(ostream& cout, Person& p) { /*cout << "姓名:" << p.name << "," << "年齡:" << p.age;*/ return cout; } void printPerson(const list<Person>& p) { for (list<Person>::const_iterator it = p.begin(); it != p.end(); it++) { cout <<"姓名:"<< (*it).name << "\t"<<"年齡:" <<(*it).age<< endl; } } bool myCompare(Person &p1, Person &p2) { //若年齡相同 if (p1.age == p2.age) { return p1.name < p2.name; } return p1.age <p2.age; } void test() { list<Person> lst; Person p1("tom", 12); Person p2("jack", 12); Person p3("sim", 16); Person p4("mike", 14); Person p5("bob", 11); Person p6("lol", 11); lst.push_back(p1); lst.push_back(p2); lst.push_back(p3); lst.push_back(p4); lst.push_back(p5); lst.push_back(p6); cout << "排序前:" << endl; printPerson(lst); lst.sort(myCompare); cout << "排序后:" << endl; printPerson(lst); } int main() { test(); system("pause"); return 0; }
輸出:
可以發現年齡已按升序排列,同時在年齡相同時,名字也是按首字母的順序按升序排列。