c++ - C ++如何在地图中打印最多输入的单词
问题描述
目前它会打印每个单词的打印次数。但是我怎样才能让它打印出重复次数最多的单词呢?
输入:5
苹果, 香蕉, 苹果, 苹果, 香蕉
输出:
3 苹果
2根香蕉
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> freq;
string word;
int max;
while (cin >> word)
{
freq[word]++;
}
map<string, int>::const_iterator iter;
for (iter = freq.begin(); iter != freq.end(); ++iter) {
cout << iter->second << " " << iter->first << endl;
}
system("pause");
}
解决方案
You can use std::max_element and a functor that compares the pair's from the map:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main() {
using mmap = map<string, int>;
mmap freq;
std::string data = "apple banana apple banana apple";
std::istringstream iss(data);
string word;
while (iss >> word)
freq[word]++;
auto iter = std::max_element(std::begin(freq), std::end(freq), []
(const mmap::value_type& a, const mmap::value_type& b)
{ return a.second < b.second; });
std::cout << iter->first << " " << iter->second;
}
Output:
apple 3
推荐阅读
- r - 将新的刻度标签名称添加到绘图
- django - 允许模型上的其他属性,例如占位符文本或图标
- django - Django:如何在不包含每个字段的情况下呈现我的表单集
(或任何其他)元素而不丢失管理形式?
- javascript - 在 Odoo 中显示或隐藏笔记本页面?
- leaflet - 在 Leaflet 地图上添加 div 元素
- azure - 从 B2C 端点接收到授权码以访问 MS Graph 后未收到访问令牌
- sikuli - 运行自动测试时,Sikuli 无法识别截图工具在屏幕上拍摄的图像
- amazon-dynamodb - 如何从 aws dynamo db 查询多个数据?
- android - 如何清除android studio ide剪贴板
- javascript - 如何在递归 javascript 调用中正确设置 return 语句?