sort (first,last,cmp); //对[first,last) 之间的进行排序 注意最后一个last是不包括的
cmp是比较函数 是一个自定义的比较规则 对于cmp函数的编写的利用sort函数的关键
下面看应用实例
pat 1028 甲级 题目
https://pintia.cn/problem-sets/994805342720868352/problems/994805468327690240
代码如下 注意看代码中的3个cmp函数以及解析 这3个函数都是在结构体中的利用 如果是基本数据类型 直接把typename改一下就好
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct student {
int id;
string name;
int grade;
}stu[100010];
bool cmp1( student a, student b){
//按id升序在前面
return a.id<b.id;
}
bool cmp2( student a, student b){
// 按名字升序排序 要是名字一样 按id升序排序 因为name是字符串 会按照字典序来排序
if(a.name != b.name) return a.name<b.name;
else return a.id< b