- 用法一:数组排序
对一个数组进行升序排序
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a[100]={8,9,10,6,5,4};
sort(a,a+6);
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
sort包含在#include<algorithm>中,sort(数组头,数组尾),sort(a,a+6)可以看作sort(a+0,a+6)表示对数组a的第0个元素到第5个元素进行排序。默认排序方式为升序排序。
如果想进行降序排序则需要引入自定义排序规则compare
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
bool compare(int a,int b){
return a>b;
}
int main()
{
int a[100]={8,9,10,6,5,4};
sort(a,a+6,compare);
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
- 用法2:结构体排序
有时我们会遇到这样的问题,按学生成绩进行降序排序,如果成绩相同按学号升序排序,怎么用sort解决这个问题呢?
struct student{
int num; //学号
int score; //成绩
};
bool cmp(student a,student b){//按成绩降序,再按学号升序
if(a.score>b.score)return a.num<b.num;
return a.score>b.score;
}
struct student stu[10];
//输入学生数据
sort(a,a+10,cmp);
- 用法3:动态数组vector内的排序
vector<int>s;
sort(s.begin(),s.end());
注意事项:sort内集成了多种算法,时间复杂度会比n*n小但并不是nlogn