Bootstrap

C++复习(十):比较函数的书写

正常写法

struct student{
    int score1;
    int score2;
};

//若返回值为True则a排在b前面,否则a排在b后面。
bool cmp(const student &a, const student &b)
{
    return (a.score1 > b.score1)||((a.score1 == b.score1)&&(a.score2 > b.score2));
}

匿名函数写法

#include<vector>
#include<algorithm>

vector<student> v;
//第三个参数为比较器的匿名函数写法
sort(v.begin(),v.end(),[](const student &a, const student &b){
    return (a.score1 > b.score1)||((a.score1 == b.score1)&&(a.score2 > b.score2));
    })

有些库函数需要的比较器是一个类,这时应当写成下面这样

//这个比较器的结构体中重载了小括号操作符
struct cmp{
    bool operator()(const student &a, const student &b){
        return (a.score1 > b.score1)||((a.score1 == b.score1)&&(a.score2 > b.score2));
    }
}

当然如果不想写比较器,我们可以直接对类的“<”操作符进行重载

struct student{
    int score1;
    int score2;
    bool operator<(const student &a, const student &b){
        return (a.score1 > b.score1)||((a.score1 == b.score1)&&(a.score2 > b.score2));
    }
};

 

;