简述
- 头文件:
#include < algorithm>
using namespace std;
对数组排序
数组名为a
共有n个数
sort(a,a+n);
- 此方法默认升序排
- 如果要降序排,则要定义一个cmp函数
bool cmp(int a,int b){
return a>b;
}
......
sort(a,a+n,cmp);
对结构体排序
- 要根据自己想要的写cmp函数
- 举个栗子
struct student{
int high;
int weight;
};
struct student a[105];
- 上面是一个结构体,我们现在想把学生按身高由小到大排个序,cmp函数的写法如下:
bool cmp(struct student a,struct student b){
return a.high <b.high ;
}
......
sort(a,a+n,cmp);
- 但如果说有的学生可能身高相同,我们按身高由小到达排序时,如果碰上身高相同的,则按体重由大到小排,cmp的写法如下
bool cmp(struct student a,struct student b){
if(a.high==b.high)
return a.weihgt>b.weight;
return a.high <b.high ;
}
......
sort(a,a+n,cmp);