查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
示例:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
jack 70
Tom 70
peter 96
#include<iostream>
#include <iomanip>
#include <algorithm>using namespace std;typedef struct student {string name;int grade;int squeue;
} student;bool compare1(student a, student b) {if (a.grade != b.grade) {return a.grade < b.grade;} else {return a.squeue < b.squeue;}}bool compare2(student a, student b) {if (a.grade != b.grade) {return a.grade > b.grade;} else {return a.squeue < b.squeue;}
}int main() {int n = 0, way = 0;while (::scanf("%d %d", &n, &way) != EOF) {student cla[n];for (int i = 0; i < n; ++i) {cin >> cla[i].name >> cla[i].grade;cla[i].squeue=i;}if (way == 1) {sort(cla, cla + n, compare1);} else {sort(cla, cla + n, compare2);}for (int i = 0; i < n; ++i) {cout << cla[i].name << " " << cla[i].grade << endl;}}return 0;}
这道题总体不难,只有一个需要注意的细节,只要成绩相同就按照先后顺序来填,所以在编写compare1和compare2函数的时候,对squeue的比较代码是相同的