C++ List中的排序使用实例

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

using namespace std;

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

    string m_name;
    int m_age;
    int m_height;
};
bool compare(Person &p1,Person &p2)
{
    //年龄相同的按身高降序排列
    if(p1.m_age == p2.m_age){
        return p1.m_height>p2.m_height;
    }else{
        return p1.m_age<p2.m_age;//按年龄升序排列
    }
   
}
void test()
{
        Person p1("刘备",35,175);
        Person p2("曹操",45,188);
        Person p3("孙权",48,170);
        Person p4("赵云",25,198);
        Person p5("张飞",35,160);
        Person p6("关羽",35,200);

        list<Person> myL;
        myL.push_back(p1);
        myL.push_back(p2);
        myL.push_back(p3);
        myL.push_back(p4);
        myL.push_back(p5);
        myL.push_back(p6);

        for(list<Person>::iterator it = myL.begin();it != myL.end();it++){
            cout<<"姓名: "<<it->m_name<<" 年龄 :"<<it->m_age<<" 身高 :"<<it->m_height<<endl;
        }

        cout<<"-----------------"<<endl;

        //按年纪大小排序
        myL.sort(compare);//使用list里面的成员函数,使用仿函数指定排序方法
        for(list<Person>::iterator it = myL.begin();it != myL.end();it++){
            cout<<"姓名: "<<it->m_name<<" 年龄 :"<<it->m_age<<" 身高 :"<<it->m_height<<endl;
        }


}
int main()
{

    test();
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值