详解C++ sort函数的cmp参数

前言:

学算法的第一天你在学冒泡、桶排

在你还没搞明白快排和归并的时候

你已经学到了数据结构最后的堆排序和希尔排序

可以说排序是很多竞赛生的噩梦……

于是它诞生了

void std::sort()

Sort the elements of a sequence using a predicate for comparison.

参数:
__first – An iterator.
__last – Another iterator.
__comp – A comparison functor.

针对一个地址区间完成排序,算法每次自动选择,以快排为主

C++需要头文件#include <algorithm> (当然万能头我也没意见)

1、升序排序

最简单的就是用它完成int类型升序排序

Copy Line-numbers language-cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int a[5] = {2, 1, 3, 5, 4};
    sort(a, a + 5);
    for (int i = 0; i < 5; i++) cout << a[i] << " ";
}


输出如下,很简单

1 2 3 4 5

这里传入给sort的参数 a a + 5 都是地址,和大多数编程语言一样,这里遵循左闭右开原则,即函数实际会读取和操作的五个地址如下:

a + 0
a + 1
a + 2
a + 3
a + 4

2、降序排序

如果需要降序排序,程序如下

#include <iostream>
#include <algorithm>
using namespace std;

bool cmp(int x, int y){
    return x > y;
}

int main() {
    int a[5] = {2, 1, 3, 5, 4};
    sort(a, a + 5, cmp);
    for (int i = 0; i < 5; i++) cout << a[i] << " ";
}

输出:

5 4 3 2 1

我们多写了一个bool类型的cmp函数,并将其地址作为第3个参数传给了sort

cmp可以替换其内置的函数来判断究竟该让哪些元素在前哪些元素在后

很多小伙伴可能有个疑惑:如何从实质上理解cmp函数,或者说我究竟该怎么记住cmp怎么写呢?

我们来看这三个点:

  • 毋庸置疑,cmp函数返回bool类型,表示当前排序是否正确(具体见3)
  • cmp函数应接受两个参数,类型与要排序的数组相同(可以是int、short和long long这些常见类型,当然也可以是结构体)
  • cmp返回值的实际意义是传入a、b两个参数,a在前b在后的排序是否是正确的,若是正确的返回1(true),否则返回0(false)

那么我们再看一个结构体的排序实例

3、结构体的排序实例

结构体的排序实例:输入10个学生的名字和成绩,按照成绩从高到低排序后输出

输入数据:

Yixiangzhilv 90
Mydr 60
Xiaoming 10
Mr.Glass 60
GZN 80
Wangzi 85
Hyx 100
Wyx 99
Xth 0
Zz 75

程序实现如下:

#include <algorithm>
#include <iostream>
using namespace std;

struct node {
    string name;
    int score;
};

bool cmp(struct node x, struct node y) {
    return x.score > y.score;
}

int main() {
    struct node a[10];
    for (int i = 0; i < 10; i++) cin >> a[i].name >> a[i].score;
    sort(a, a + 10, cmp);
    for (int i = 0; i < 10; i++) cout << a[i].name << " " << a[i].score << endl;
}

(此处还有一个C++知识:如果已经定义结构体node,那么 struct node a[10]; 和 node a[10]; 都是合法的)