STL自定义比较函数

调用sort函数需要加头文件<algorithm>

sort函数默认的比较函数为(简化)

bool comp(int a,int b){

return a<b;

}

即默认排序为从小到大,如果想从大到小,只需要作如下修改

bool comp(int a,int b){

return a<b;

}

调用sort函数时,显性调用comp函数,sort(begin,end,comp)

 

结构体自定义排序规则

有两种方法,举例说明

在结构体内重载运算符<

struct temp{

int w;

int p;

temp(){

w=0;

p=0;

}

bool operator <(const temp &t)const{

return w<t.w     //按w的大小从小到大排列

}

}

定义比较函数,与前面相同

posted @ 2015-02-08 21:56  celinecoding  阅读(407)  评论(0编辑  收藏  举报