题解 | #成绩排序#sort+cmp+结构体+数组+二次排
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include "cstdio"
#include "algorithm"
using namespace std;
struct Student {
char name[100];
unsigned int score;
unsigned int seq;
};
bool comp_asc(struct Student stu1, struct Student stu2) {
if (stu1.score < stu2.score) {
return true;
} else if (stu1.score == stu2.score) {
return stu1.seq < stu2.seq;
}
return false;
}
bool comp_desc(struct Student stu1, struct Student stu2) {
if (stu1.score > stu2.score) {
return true;
} else if (stu1.score == stu2.score) {
return stu1.seq < stu2.seq;
}
return false;
}
int main() {
int n, asc;
while (EOF != scanf("%d %d", &n, &asc)) {
struct Student studs[n];
for (int i = 0; i < n; ++i) {
int id, score;
scanf("%s %d", studs[i].name, &studs[i].score);
studs[i].seq = i;
}
if (1 == asc) {
sort(studs, studs + n, comp_asc);
} else {
sort(studs, studs + n, comp_desc);
}
for (int i = 0; i < n; i++) {
printf("%s %d\n", studs[i].name, studs[i].score);
}
}
return 0;
}


查看7道真题和解析