【发布时间】:2016-08-29 12:59:58
【问题描述】:
编写一个 C++ 程序,要求用户输入一个整数 m,然后输入 m 个其他学生的姓名和代表他们最终成绩的数字(满分 100)。每次,用户都必须输入姓名和成绩。姓名和成绩将存储在单独的列表中。
在获取所有姓名和成绩后,程序会查找并显示最高成绩和拥有该成绩的学生的姓名
我试过了,能拿到最高分,但是名字我写错了……
plzzzzzzzzzzzzzzzzzzzzz 帮助!!!!!!
#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;
}
【问题讨论】:
-
如果没有
std::max_element/std::distance,我会使用std::vector和索引。 -
grades.pop_back();可疑
标签: c++ list data-structures iterator