list列表排序功能!

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

bool compare_id(int first,int next)
{
    if( first < next )
        return false;
    else
        return true;
}
/*
 enter a group of several number,and from small to large order.
*/
int main(int argc,char *argv[])
{
    int id = 0;
    list<int> tmp;
    list <int>::iterator it;
    //1.enter numbers
    cout<<"Please enter some numbers(enter 0 to exit!)";
    do
    {
        cin>>id;
        tmp.push_back(id);
    }while(id);

    //2.sort default
    tmp.sort();
    cout << "Sort after is(default) :"<<"\n";
    for(it=tmp.begin();it!=tmp.end();it++)
    {
        cout << " "<<*it;
    }
    cout << "\n";

    //3. sort compare 
    tmp.sort(compare_id);
    cout << "Sort after is(compare) :"<<"\n";
    for(it=tmp.begin();it!=tmp.end();it++)
    {
        cout << " "<<*it;
    }
    cout << "\n";
    return 0;
}

执行结果:

# g++ test.cpp
# ./a.out
Please enter some numbers(enter 0 to exit!)23 1 24 45 64 34 0
Sort after is(default) :
 0 1 23 24 34 45 64
Sort after is(compare) :
 64 45 34 24 23 1 0
#

备注:
list.sort()是默认排序,按从小到大排序。
回调函数compare()中入参类型必须同list的类型相同!
compare()函数返回值类型为bool类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值