题目
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 1 个测试用例,格式为
第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
… … …
第 n+1 行:第 n 个学生的姓名 学号 成绩
其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:
对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。
思路
初始看到题的时候就是回忆起了之前数据结构上课的链表了,但仔细看这道题目要求的功能只有存储最高与最低两串数据,则改变思路通过创建最高与最低两个结构体,通过比较成绩高低来存储。
代码
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name, id;
int score;
Student(int x) :score(x) {}
};
int main()
{
int n, sc;
Student high(0), low(100);//创建最高并初始化成绩为0与创建最低并初始化为100
string name, id;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> name >> id >> sc;
if (sc > high.score)
{
high.name = name;
high.id = id;
high.score = sc;
}if (sc < low.score)
{
low.name = name;
low.id = id;
low.score = sc;
}
}
cout << high.name << " " << high.id << " " << high.score << endl;
cout << low.name << " " << low.id << " " << low.score << endl;
return 0;
}
了解到C++中可以在结构体内定义成员函数,而非像C只能使用函数指针,所以作者对后来又添加了一个成员函数用来进行存储。
struct Student
{
string name, id;
int score;
Student(int x) :score(x) {}
void Read(string name, string id, int score)
{
this->name = name;
this->id = id;
this->score = score;
}
};
之后赋值的部分就可以简写
if (sc > high.score)
high.Read(name, id, sc);
if (sc < low.score)
low.Read(name, id, sc);
但在做出这样的修改之后,程序的使用时间开始飘忽不定。修改前完成时间大多在5、6ms之间,而修改后虽然也有5ms左右,但大多都飙升至了15ms开外。按照目前作者水平暂时不知道原因,但猜想应该在每一次循环中调用函数的消耗大于直接赋值的消耗。