C++映射迭代器



程序只打印重复次数最多的单词。如果没有最重复的单词来打印错误或";没有";?

输入:5苹果香蕉苹果香蕉

输出:苹果

如果说,我希望它显示

输入:苹果香蕉

输出:";none";

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
using mmap = map<string, int>; mmap freq;
int n; cin >> n;
string word;
if (n < 1 && n > 100000) return 0;
for (int i = 0; i < n; i++)
{
cin >> word;
freq[word]++;
}
auto iter = max_element(begin(freq), end(freq), []
(const mmap::value_type& a, const mmap::value_type& b)
{ return a.second < b.second; });
cout << iter->first << " ";;
system("pause");
}

std::max_element()的使用是将iterator返回到具有最大second值的第一个元素。

然后,您可以使用std::any_of()std::none_of()来检查是否还有其他元素具有相同的second值:

auto iter = max_element(begin(freq), end(freq), [](const mmap::value_type& a, const mmap::value_type& b) { return a.second < b.second; }); 
if ((iter == end(freq)) || any_of(next(iter), end(freq), [&](const mmap::value_type& a){ return a.second == iter->second; }))
cout << "none";
else
cout << iter->first;

现场演示

auto iter = max_element(begin(freq), end(freq), [](const mmap::value_type& a, const mmap::value_type& b) { return a.second < b.second; }); 
if ((iter != end(freq)) && none_of(next(iter), end(freq), [&](const mmap::value_type& a){ return a.second == iter->second; }))
cout << iter->first;
else
cout << "none";

现场演示

最新更新