读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 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
思路是让姓名、学号和成绩分开存储,下标都是一一对应的,所以通过最大和最小成绩的下标来找到姓名和成绩。
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(int argc, char** argv) {
vector<string> name;
vector<string> num;
vector<int> score;
int n;
cin >> n;
string tempname, tempnum;
int tempscore;
for (int i = 0; i < n; i++) {
//没有办法直接使用数组的方式对vector进行输入,所以使用变量来替代接收一下
cin >> tempname >> tempnum >> tempscore;
name.push_back(tempname);
num.push_back(tempnum);
score.push_back(tempscore);
}
//max_element返回一个迭代器, 该迭代器指向在[first, last)范围内具有最大值的元素
int big = *max_element(score.begin(), score.end());
//find可以查找[first, last)范围内,等价的第一个元素,返回一个迭代器。如果没有这个元素,将返回last
int maxposition = find(score.begin(), score.end(), big) - score.begin();
//min_element和max_element同理,不过返回的是最小值
int small = *min_element(score.begin(), score.end());
int minposition = find(score.begin(), score.end(), small) - score.begin();
cout << name[maxposition] << " " << num[maxposition] << endl;
cout << name[minposition] << " " << num[minposition] << endl;
return 0;
}