循环次数比我预期的要多

Looping more times than I expect

本文关键字:循环      更新时间:2023-10-16

>我有以下函数,它采用学生(具有姓名和注册号)的向量,然后计算这些学生的最小,最大和平均分数(他们的分数存储在地图中),输出部分正确,它应该只打印每个学生一次,但是我编写的代码打印出每个学生的次数与存储在其向量中的标记数量相同。我花了一些时间试图解决这个问题,我相信问题是我的第三个 for 循环,有人可以解释为什么它像这样循环以及如何解决它。谢谢。

string func1(vector<Student>students, float mark) {
    int count = 0;
    float avg, min, max = 0;
    list<string> toPrint;
    map<string, float> temp;
    vector<float> v;
    //for every student
    for(size_t a=0; a < students.size(); ++a) {
        temp = students[a].getCopyOfMap();
        v.erase(v.begin(), v.end());
        avg = 0;
        min = 0;
        max = 0;
        count = 0;
        for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
            stringstream ss;
            ss << it->second;
            v.push_back(stof(ss.str()));
        }
        for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
            max = *max_element(v.begin(), v.end());
            min = *min_element(v.begin(), v.end());
            for (size_t b=0; b < v.size(); ++b) {
                avg = avg + v[b];
                count++;
            }
            avg = avg/count;
            if(avg > mark) {
                stringstream out;
                out << students[a].getRegNo() << " " << min << " " << max << " " << avg << endl;
                toPrint.push_back(out.str());
            }
        }
    }

你的"if"语句应该在你的第三个"for"之外,但仍在第一个"for"之内。