头文件:
#include<algorithm>//sort头文件几种排序准则实例:
bool cmp1(int x,int y){
return x>y;//从小到大进行排序
}bool cmp2(int x,int y){
return x%10>y%10;
}bool cmp3(node x,node y){
if(x.a!=y.a){
return x.a<y.a;
}
return x.b<y.b;
}bool cmp4(node x,node y){
int aa=x.a+x.b;
int bb=y.a+y.b;
return aa>bb;
}完整代码:
#include<iostream>
#include<algorithm>//sort头文件
using namespace std;
const int n=5;
struct node{
int a,b;
string str;
}ch[10];
bool cmp1(int x,int y){
return x>y;//从小到大进行排序
}
bool cmp2(int x,int y){
return x%10>y%10;
}
bool cmp3(node x,node y){
if(x.a!=y.a){
return x.a<y.a;
}
return x.b<y.b;
}
bool cmp4(node x,node y){
int aa=x.a+x.b;
int bb=y.a+y.b;
return aa>bb;
}
int main(){
int i,j,k;
for(i=1;i<=n;i++)cin>>ch[i].a;
sort(ch+1,ch+1+n,cmp3);//注意是ch+1
for(i=1;i<=n;i++)cout<<ch[i].a<<endl;
return 0;
}
The end!
该文展示了在C++中如何使用sort函数进行不同准则的排序,包括基于整数大小、个位数大小以及结构体成员的排序。示例中定义了多个比较函数cmp1至cmp4,并在main函数中对结构体数组按照cmp3进行排序并打印结果。
1782

被折叠的 条评论
为什么被折叠?



