c++实现对自定义数据类型进行排序

1. 场景说明

      一个Person类,具有age和height属性,按照age降序排列;如果age相同,则按照height降序排列。

2. 代码实现

#include <iostream>
#include <list>
#include <string>

using namespace std;

class Person
{
public:
    Person(string name, int height, int age)
    {
        this->m_name = name;
        this->m_height = height;
        this->m_age = age;
    }

    string m_name;
    int m_height;
    int m_age;
};


void printList(list<Person>&L)
{
    for(list<Person>::iterator it=L.begin(); it != L.end(); it ++)
    {
        cout << "name:" << it->m_name << ", height:" << it->m_height << ", age:" << it->m_age << endl;
    }
}


class Compare
{
public:
    bool operator()(Person &p1, Person &p2)
    {
        if(p1.m_age == p2.m_age)
        {
            return p1.m_height > p1.m_height;
        }
        else
        {
            return p1.m_age > p2.m_age;
        }
    }
};


int main()
{
    list<Person>L;
    Person p1("guopei", 175, 30);
    Person p2("guofan", 170, 28);
    Person p3("guorong", 170, 32);
    Person p4("caige", 160, 28);
    Person p5("caipei", 170, 30);
    Person p6("huqiang", 170, 32);

    L.push_back(p1);
    L.push_back(p2);
    L.push_back(p3);
    L.push_back(p4);
    L.push_back(p5);
    L.push_back(p6);

    printList(L);

    cout << "-----------------------------" << endl;
    L.sort(Compare());
    printList(L);

    return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值