c++ - 如何在字符串的二维向量中找到最大平均标记?
问题描述
我在字符串的二维向量中获取了每个学生的姓名和分数。我们如何找到平均分最高的学生姓名
我无法获取学生的分数,因为它是二维向量中的字符串。我可以使用 STL Map 来做同样的事情。但是如何使用字符串的二维向量来做同样的事情。
vector<vector<string>>vect {{"James", "70"}, {"Fernando", "40"}, {"Nick", "60"},{"James", "90"},{"Nick", "70"},{"Amit", "50"}};
预期输出是“詹姆斯:80”
解决方案
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.)
推荐阅读
- python - 在 Windows 10 上安装 CMake 后无法导入 OpenCV
- sql-server - 使用 GROUP BY 选择所有具有明细表列约束的主表行
- r - 将具有相同后缀的多个变量的值重新编码为R中具有不同后缀的新变量
- python - 由不同进程填充的共享字典
- module - 如何将模块添加到环境模块?所以我可以使用模块加载来加载它
- javascript - 如何将 glTF 对象添加到场景中?
- typescript - TypeScript 元编程:推断私有类型?
- python - 正在接收 Discord bot 命令,但未执行命令
- python - 如何在我的评分系统上用 python 编写更简单的代码
- java - 将静态数据存储在 DB 或 Spring yml 属性文件中