

本题是进行分类排序,但是开始确实是不会,所以是参考别人的代码抄下来的。本题重点是对每组数据进行分类,将说明好的进行分类,然后未说明的,其他的情况直接else;还有一个难点是分类排序,要自己写cmp函数,下面会有对sort排序的讲解和对strcmp的讲解:


sort函数需要头文件#include,strcmp需要头文件#include<string.h>(在pta需要加上.h,VS2012不需要),下面是完整的源码:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
struct info {
char num[10];
int de, cai, sum;
int clas;
}stu[100001];
bool cmp(info a, info b) {
if (a.clas != b.clas)return a.clas < b.clas;
else if (a.sum != b.sum)return a.sum > b.sum;
else if (a.de != b.de)return a.de > b.de;
else return strcmp(a.num, b.num) < 0;
}
int main() {
int n, l, h;
cin >> n >> l >> h;
int cnt = n;
for (int i = 0; i < n; i++) {
cin >> stu[i].num >> stu[i].de >> stu[i].cai;
stu[i].sum = stu[i].de + stu[i].cai;
if (stu[i].de < l || stu[i].cai < l) {
stu[i].clas = 5;
cnt--;
}
else if (stu[i].de >= h && stu[i].cai >= h)stu[i].clas = 1;
else if (stu[i].de >= h && stu[i].cai < h)stu[i].clas = 2;
else if (stu[i].de < h&&stu[i].cai < h&&stu[i].de >= stu[i].cai)stu[i].clas = 3;
else stu[i].clas = 4;
}
sort(stu, stu + n, cmp);
cout << cnt << endl;
for (int i = 0; i < cnt; i++)
cout << stu[i].num << " " << stu[i].de << " " << stu[i].cai << endl;
return 0;
}
这篇博客介绍了如何使用C++进行数据分类排序,重点在于理解如何定义比较函数cmp进行多条件排序。代码中首先定义了一个包含学生信息的结构体,然后根据输入的成绩对学生成绩进行分类,最后使用sort函数进行排序。排序依据为类别、总分、德育分,如果类别和总分相同,则按姓名排序。
393

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



