sort函数的使用
要加头文件#include
sort函数的使用,从大到小改写,结构体改写排序
#include<iostream>
#include<algorithm >
using namespace std;
int n=5;
int a[5]={4,1,2,8,6};
struct time{
int start;
int end;
};
int cmp1(int a,int b){
return a>b;
}
int cmp2(time a,time b){
return a.end<b.end;
}
void Print(){
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main(){
Print();
sort(a,a+n);
cout<<"从小到大排序:";
Print();
sort(a,a+n,cmp1); //改写sort函数从大到小排序
cout<<"从大到小排序:";
Print();
cout<<"结构体排序-输入n和2*n个数:";
struct time t[100];
cin>>n;
for(int i=0;i<n;i++){
cin>>t[i].start >>t[i].end;
}
sort(t,t+n,cmp2);//结构体调用Sort函数
cout<<"结构体排序:按end从小到大排序\n";
for(int i=0;i<n;i++){
cout<<t[i].start <<" "<<t[i].end<<" \n";
}
return 0;
}
/*
9
9 12
8 10
20 23
8 15
11 14
12 16
15 17
18 21
16 18
*/