list容器案例

案例描述:将person自定义数据类型进行排序,person中属性有姓名,年龄,身高

排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序

//案例描述:将person自定义数据类型进行排序,person中属性有姓名,年龄,身高
//排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序

#include<iostream>
using namespace std;
#include<string>
#include<list>

class person
{
public:
        person(string name, int age, int height)
        {
                this->name = name;
                this->age = age;
                this->height = height;
        }

        string name;
        int age;
        int height;
};

bool compare(person &p1,person &p2)
{
        if (p1.age == p2.age)
        {
                return p1.height > p2.height;
        }
        else
        {
                return p1.age < p2.age;
        }
}

void test1()
{
        list<person> l;
        person p1("张三", 25, 165);
        person p2("李四", 35, 210);
        person p3("王五", 35, 186);
        person p4("赵六", 35, 189);
        person p5("何九", 46, 164);
        person p6("贾八", 49, 175);
        person p7("权十", 49, 198);

        l.push_back(p1);
        l.push_back(p2);
        l.push_back(p3);
        l.push_back(p4);
        l.push_back(p5);
        l.push_back(p6);
        l.push_back(p7);

        for (list<person>::iterator it = l.begin(); it != l.end(); it++)
        {
                cout << " 姓名为: " << (*it).name << " 年龄为: " << (*it).age << " 身高为: " << it->height << endl;

        }

        //排序
        cout << "--------------------------------------" << endl;
        l.sort(compare);
        for (list<person>::iterator it = l.begin(); it != l.end(); it++)
        {
                cout << " 姓名为: " << (*it).name << " 年龄为: " << (*it).age << " 身高为: " << it->height << endl;

        }
}

int main()
{
        test1();
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值