sort函数是基于排序的库函数,可以通过调用<algorithm>头文件来调用
sort(a,b,cmp),sort()函数有三个参数,分别为起点指针,终点指针,比较函数,如果不写比较函数,则默认从小到大排列。
sort()是经过优化的排序方法,时间复杂度为O(nlogn)
以下是一些具体使用sort()函数的例子
用数组实现排序
#include<bits/stdc++.h>
using namespace std;
int arr[]={2,3,4,1,6};
//实现从大往小排
bool cmp(int a,int b){
return a>b;
}
int main(){
sort(arr,arr+5,cmp);
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
return 0;
}
用vector实现排序
#include<bits/stdc++.h>
using namespace std;
vector <int> arr({2,3,4,1,6});
//实现从大往小排
bool cmp(int a,int b){
return a>b;
}
int main(){
//vector类型需要用迭代器
sort(arr.begin(),arr.end(),cmp);
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
return 0;
}
用结构体实现排序
#include<bits/stdc++.h>
using namespace std;
struct Rec{
int x,y;
//重载小于号
bool operator<(const Rec &t) const{
return x>t.x;
}
}a[5];
//实现从大往小排
bool cmp(int a,int b){
return a>b;
}
int main(){
for(int i=0;i<5;i++){
a[i].x=-i;
a[i].y=i;
}
sort(a,a+5);
for(int i=0;i<5;i++){
cout<<a[i].x<<" ";
}
return 0;
}