前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++STL容器之使用list容器对自己定义的数据类型进行排序

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

作者头像
西西嘛呦
发布2020-08-26 21:24:33
1.4K0
发布2020-08-26 21:24:33
举报
文章被收录于专栏:数据分析与挖掘

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

代码语言:javascript
复制
#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;
}

輸出:

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-12-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档