全班投票选班级宠物,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;
}
写好了先点「运行」试试示例,没问题再点「提交」。