首页 > 解决方案 > 如何在字符串的二维向量中找到最大平均标记?

问题描述

我在字符串的二维向量中获取了每个学生的姓名和分数。我们如何找到平均分最高的学生姓名

我无法获取学生的分数,因为它是二维向量中的字符串。我可以使用 STL Map 来做同样的事情。但是如何使用字符串的二维向量来做同样的事情。

vector<vector<string>>vect {{"James", "70"}, {"Fernando", "40"}, {"Nick", "60"},{"James", "90"},{"Nick", "70"},{"Amit", "50"}};

预期输出是“詹姆斯:80”

标签: c++algorithmc++11stdvector

解决方案


My approach: Use a map Student -> Vector of Marks, fill it, then average it.

map<string, vector<double> > marks;

for(const vector<string>& entry : vect)
{
    string name = entry[0];
    int mark = stod(entry[1]);
    marks[name].push_back(mark);
}

Now you have a map filled with a vector of marks for each student, easy to handle. If you want the averages, go like:

string best_student = "nobody";
double best_average = 0.;

for(auto const& entry : marks)
{
    const string& name = entry.first;
    const vector<double>& student_marks = entry.second;
    double average = accumulate(student_marks.begin(), student_marks.end(), 0) / student_marks.size();

    cout << "The student " << name << " has an average mark of " << average << endl;

    if(average > best_average)
    {
        best_average = average;
        best_student = name;
    }
}

cout << endl;
cout << "The student with the highest average mark is " << best_student << " with " << best_average << endl;

(Note that you need to #include<numeric> for std::accumulate, and that I used for each, thus you need at least C++11.)

Might not be the most time optimized approach, but works nicely and is quite readable as far as I see it.

I implemented this here: http://cpp.sh/6lijg

(I did some assumptions that one might check (/handle by something like throwing an exception if not met or printing some message): 1. The original vector is always correctly filled, that is every subvector has length 2; 2. the original vector always has at least one entry; 3. marks are non-negative and there is a student with a non-zero mark - else the initializations of best_student and best_mark are wrong.)


推荐阅读