编写一个 C++ 程序,要求用户输入一个整数 m,后跟 m 个学生的其他姓名和代表他们最终成绩的数字(满分 100)。每次,用户都必须输入姓名和成绩。姓名和成绩将存储在单独的列表中。
在得到所有的姓名和成绩后,程序会找出并显示最高成绩的学生姓名
我试过了,能拿到最高分,但是名字我写错了...
求助啊!!!!!!
#include <cstdlib>
#include<iostream>
#include<string>
#include<list>
using namespace std;
int main() {
list<string>names;
list<int>grades;
int m, grade;
string studentname;
cout << "Enter m names and m grades \n";
cin>>m;
for (int i = 0; i < m; i++) {
cout << "Enter students name " << i + 1 << ":" << endl;
cin>>studentname;
names.push_back(studentname);
cout << "Enter students grade " << i + 1 << ":" << endl;
cin>>grade;
grades.push_back(grade);
}
list<string>::iterator tn; //iterator tn to read a list of names
list<int>::iterator tg; //iterator tg to read a list of grades
float highest;
string name;
tn = names.begin(); //to point to the first name
tg = grades.begin(); //to point to the first grade
highest = *tg; //suppose that the highest grade is the first grade
name = *tn; //suppose that the first student has the highest grade
tg++; //to move to the next grade
tn++; //to move to the next name
for (tg; tg != grades.end(); tg++) {
if (highest<*tg) {
highest=*tg;
grades.pop_back();
}
tn++; //to read in the list of students’ names
}
cout << "----------\n";
cout << "Highest grade: " << highest << " for: " << name;
cout << "\n----------\n";
return 0;
}
最佳答案
您在循环之前将 name
设置为 name = *tn;
,并且以后永远不要更改它。你期待什么?
关于c++ - 使用 STL 列表获取最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37021802/