c++ - 使用 STL 列表获取最高值

标签 c++ list data-structures iterator

编写一个 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/

相关文章:

c++ - 输入验证不起作用

c# - 无法将扩展类转换为 IList

c++ - std::list 或 std::multimap

c++ - 具有历史的搜索结构(持久性)

c - 结构中的语法 [c]

c++ - 在 C++ 中确定 32 位和 64 位

c++ - 不会被优化掉的最简单的 "unused"代码是什么?

c++ - C++中普通类型的构造和初始化

php - 如何在 php 中列出所有国家及其州/省?

c - 在C中定义结构体数组?