c++STL容器之使用list容器对自己定义的数据类型进行排序

时间:2022-07-24
本文章向大家介绍c++STL容器之使用list容器对自己定义的数据类型进行排序,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

需求;有一个类,类中有姓名和年龄成员变量,现在要按姓名升序排序,在姓名相同时按名字升序排序。

#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;
}

輸出:

可以发现年龄已按升序排列,同时在年龄相同时,名字也是按首字母的顺序按升序排列。