#include<iostream>
#include<algorithm>
using namespace std;
struct student{
int id;
int grade[4];
};
int k;
student s[2001];
bool cmp(int a,int b){
return a>b;
}
bool cmp1(student a,student b){
return a.grade[k]>b.grade[k];
}
int main(){
int a[5]={1,3,2,4,5};
sort(a,a+5);//默认升序,即小在前
for(int i=0;i<5;i++)
cout << a[i] << " ";
cout << endl;
sort(a,a+5,cmp);//cmp中设置a>b即降序,大的在前
for(int i=0;i<5;i++)
cout << a[i] << " ";
cout << endl;
int n,m;
cin >> n >> m;
for(int i=1;i<=n;i++){
cin >> s[i].id >> s[i].grade[1] >> s[i].grade[2] >> s[i].grade[3];
}
k=1;
sort(s+1,s+n+1,cmp1);//cmp1利用结构体实现二级排序,即类二维数组以某一列排序基准
for(int i=1;i<=n;i++){
cout << s[i].id << " " << s[i].grade[1] <<" "<< s[i].grade[2] << " " << s[i].grade[3] << " " << s[i].grade[0] << endl;
}
cout << endl;
k=2;
sort(s+1,s+n+1,cmp1);
for(int i=1;i<=n;i++){
cout << s[i].id << " " << s[i].grade[1] <<" "<< s[i].grade[2] << " " << s[i].grade[3] << " " << s[i].grade[0] << endl;
}
cout << endl;
return 0;
}
输入
5 6
310101 98 85 88
310102 70 95 88
310103 82 87 94
310104 91 91 91
310105 85 90 90
输出
1 2 3 4 5
5 4 3 2 1
310101 98 85 88 271
310104 91 91 91 273
310105 85 90 90 265
310103 82 87 94 263
310102 70 95 88 253
310102 70 95 88 253
310104 91 91 91 273
310105 85 90 90 265
310103 82 87 94 263
310101 98 85 88 271
本文介绍使用C++进行数组排序的方法,包括标准库sort函数的使用及自定义比较函数实现复杂数据结构如学生信息的排序。通过具体示例展示了如何对整型数组进行升序和降序排序,以及如何基于特定字段对学生信息结构体数组进行排序。
3097

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



