STL list.sort()

list的sort(),在使用时如果不加参数那么,就会使用默认的比较器来进行排序(使用operator<),但是我们也可以自定义我们自己的比较排序标准。(The sorting is performed by applying an algorithm that uses either operator< (in version (1)) or comp (in version (2)) to compare elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without considering its reflexiveness))如下面的例子:

#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
class A{
public:
 int a,b;
 A(int t1,int t2){a=t1,b=t2;}
};

typedef struct _node{
 bool operator()(const A& t1,const A& t2)
 {
  return t1.a>t2.a;    //
 }
}node;

int main()
{
 list<A> list_a;
 A a1(1,2), a2(4,6), a3(2,8);
 list_a.push_back(a1);
 list_a.push_back(a2);
 list_a.push_back(a3);

 list_a.sort(node());

 list<A>::iterator ite;
 ite=list_a.begin();
 for(int i=0;i<3;i++) 
 {
  cout<<ite->a<<endl;
  ++ite;
 }

 return 0;

}

通过结构体node(),将class A类的对象进行了排序。显然在这里默认的比较排序是无法进行的,我们必须得针对A类对象设计一个比较方式(这个方式有node结构提供)。

实现自定义排序的要点是给结构体,或者类添加operator(),或者你也可以干脆提供一个函数(你当然也可以写一个模板来扩从性能,可参考上面链接地址的内容)。

上面的代码是在vc2005 里面编译通过的,但是在vc6.0下却不能正确编译通过。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值