#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类型。