一.基本概念
1.sort库函数包含在头文件#include<algorithm>中。是不稳定的排序,此排序方法类似于快排,时间复杂度为n * log2(n)。
2.使用方式sort(first, last,cmp)
其中first是要排序序列的起始地址,last是终止地址,cmp是排序的规则。自定义cmp函数后即可对待排序序列按规定规则排序。若不想使用第三个参数,也可使用重载运算符的方式对待排序序列进行排序。(默认是从小到大,所以可重载<运算符)
二.排序例题
方法一:
使用cmp函数自定义排序规则
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct E{
char name[101];
int age;
int score;
}buf[1000];
bool cmp(E a,E b){//实现比较规则
if(a.score!=b.score)
return a.score<b.score;//若分数不相等,则分数优先,低分数在前,高分数在后
int tmp=strcmp(a.name,b.name);
if(tmp!=0)
return tmp<0;//若分数相同,则名字字典序小的在前
else
return a.age<b.age;//若名字也相同,则年龄小的在前
}
int main(){
int n;
while(~scanf("%d",&