B1004成绩排名

读入 n(>)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。

输入格式:

每个测试输入包含 1 个测试用例,格式为

1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩 ... ... ... 第 n+1 行:第 n 个学生的姓名 学号 成绩 
 

其中姓名学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。

输出格式:

对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。

输入样例:

3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
 

输出样例:

Mike CS991301
Joe Math990112

思路:

•使用容器vector定义结构体Students类型的动态数组stu(n),注意先定义n且输入n,然后再使用;

•定义结构体某成员的排序函数cmp(),使用sort函数排序,得到以stu.score为顺序的整体结构体排序。

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 using namespace std;
 6 struct Students
 7 {
 8     string name;
 9     string id;
10     int score;
11 };
12 //定义两个Students类型的结构体,比较其中的成员score
13 bool cmp(Students a, Students b) {
14     return a.score < b.score;
15 }
16 int main() {
17     int n;
18     cin>>n;
19     vector<Students>stu(n);
20     for (int i = 0; i < n; i++) {
21         cin >> stu[i].name >> stu[i].id >> stu[i].score;
22     }
23     sort(stu.begin(), stu.begin() + n,cmp);
24     cout << stu[n - 1].name << " " << stu[n - 1].id << endl;
25     cout << stu[0].name << " " << stu[0].id << endl;
26     return 0;
27 }

猜你喜欢

转载自www.cnblogs.com/PennyXia/p/12288044.html