码迷,mamicode.com
首页 > 编程语言 > 详细

C++<algorithm>中sort的比较函数写法(转)

时间:2015-02-21 18:49:09      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

转自:http://www.wl566.com/biancheng/98907.html

C++<algorithm>中sort的比较函数写法,有需要的朋友可以参考下。

 

定义排序函数:

方法1:声明外部比较函数

bool Less(const Student& s1, const Student& s2)
{
    return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);

注意:比较函数必须写在类外部(全局区域)或声明为静态函数

 

当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。

否则,会出现错误

 

 

方法2:重载类的比较运算符

bool operator<(const Student& s1, const Student& s2)
{
    return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end());

方法3:声明比较类

struct Less
{
    bool operator()(const Student& s1, const Student& s2)
    {
        return s1.name < s2.name; //从小到大排序
    }
};

std::sort(sutVector.begin(), stuVector.end(), Less());

 

 

C++<algorithm>中sort的比较函数写法(转)

标签:

原文地址:http://www.cnblogs.com/nihow/p/4297102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!