全班投票選班級寵物,votes 記著每種寵物得了幾票。寫 top_pet(votes),返回票最多的那個。票一樣多時,要字母順序靠前的;沒人投票(空的)就返回 ""。
top_pet({{"cat", 12}, {"dog", 15}, {"fish", 3}})→'dog'top_pet({})→''string top_pet(const map<string, int> &votes)#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;
}
寫好了先點「執行」試試示例,沒問題再點「提交」。