头文件
“algorithm”
函数语法
sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,如果没有的话,默认以非降序排序。
以int为例的基本用法
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[6] = {1, 17, 60, 2, 5,12};
sort(a, a + 6);
for (int i = 0; i < 5; i++)
cout << a[i] << endl;
return 0;
}
自定义cmp函数(降序)
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int x,int y){
return x>y;
}
int main() {
int a[6] = {1, 17, 60, 2, 5,12};
sort(a, a + 6,cmp);
for (int i = 0; i < 6; i++) cout << a[i] << ' ';
return 0;
}
在结构体中运用(先按k升序,再按m降序)
#include <iostream>
#include <algorithm>
using namespace std;
struct st{
int k;
int m;
}s[100];
bool cmp(st x,st y){
if(x.k<y.k){
return true;
}
else if(x.k==y.k){
if(x.m>y.m){
return true;
}
}
else return false;
}
int main() {
int n;
sort(s,s+n,cmp);
return 0;
}