Kodewick
开始学 →
基础←→0 / 60

班级宠物投票

#033基础map循环约 5 分钟

全班投票选班级宠物,votes 记着每种宠物得了几票。写 top_pet(votes),返回票最多的那个。票一样多时,要字母顺序靠前的;没人投票(空的)就返回 ""。

示例
top_pet({{"cat", 12}, {"dog", 15}, {"fish", 3}})→'dog'
top_pet({})→''
函数string top_pet(const map<string, int> &votes)
main.cpp
#include <map>
#include <string>
using namespace std;

string top_pet(const map<string, int> &votes) {
    string best = "";
    int most = -1;
    for (const auto &p : votes) {
        // 在这里写:票比 most 多,就记下它
    }
    return best;
}
Ctrl + Enter 也能运行
结果

写好了先点「运行」试试示例,没问题再点「提交」。