双向链表list类模板有成员函数sort(),效果是从小到大排序。但事实上,sort()可以接受一个函数指针或函数对象的参数, 实现个性化的排序需求。
例题 “白给的list排序”
【描述】
程序填空,产生指定输出:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main()
{
double a[] = {1.2,3.4,9.8,7.3,2.6};
list<double> lst(a,a+5);
lst.sort(
//***********************************
//*********在此处补充你的代码********
//***********************************
);
for(list<double>::iterator i = lst.begin(); i != lst.end(); ++i)
cout << * i << "," ;
return 0;
}
【输入】
无
【输出】
9.8,7.3,3.4,2.6,1.2,
【解答】
greater<double>()
来源:OJ
此处使用了STL类模板greater中的成员函数:
template<class T>
struct greater: public binary_function<T, T, bool>
{
bool operator()(const T&x, const T&y)const{return x>y;}
};
同理可以自行编写函数对象实现个性化的排序。
【说明】
vector中的sort()
可以接受rbegin()
, rend()
参数实现倒排。而list容器中的sort()
函数不能接受这样的参数,但能接受比较函数作为实参,在功能上算是一定的弥补。