出现最多的是哪个词
运行下面这段程序:
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#include <unordered_map>
int main() {
vector<string> words = {"苹果", "香蕉", "苹果", "梨", "香蕉", "苹果"};
unordered_map<string, int> count;
for (const string& w : words) count[w] = count[w] + 1;
string best;
for (const auto& kv : count) {
if (best.empty() || kv.second > count[best]) best = kv.first;
}
cout << best << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论