题目描述:
用一维数组存储学号和成绩,然后按成绩排序后输出。
输入:
输入的一行中包括一个整数N,他代表学生的个数。
接下来的n行中,每行包括两个整数p和q,分别代表每个学生的学号和成绩。
输出:
按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。
如果学生的成绩相同,那么按照学号的大小从小到大排序。
样例输入:
3
1 90
2 87
3 92
样例输出:
2 87
1 90
3 92
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct student {
int number;
int score;
};
const int maxn = 100;
student arr[maxn];
bool compare(student x, student y) {
if (x.score == y.score) {
return x.number < y.number;
} else {
return x.score < y.score;
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &arr[i].number, &arr[i].score);
}
sort(arr, arr + n, compare);
for (int i = 0; i < n; i++) {
printf("%d %d\n", arr[i].number, arr[i].score);
}
return 0;
}
注意,这个代码里面定义了一个比较函数。
如何定义这个比较函数:当比较函数的返回值为true时,表示的是比较函数的第一个参数将会排在第二个参数前面。