Kodewick
開始學 →
基礎←→0 / 86

班級寵物投票

#033基礎for (const auto &p : votes)約 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 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。