gpt4 book ai didi

C++ 映射迭代器

转载 作者:行者123 更新时间:2023-11-30 04:54:27 25 4
gpt4 key购买 nike

程序只打印出重复次数最多的单词。没有最重复的词打印error或者“none”怎么办?

Input: 5 apple apple banana apple banana

Output: apple

如果让我们说,我希望它显示

Input: apple banana

Output: "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() 的使用是将 迭代器 返回到具有最大 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;

Live demo

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";

Live demo

关于C++ 映射迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53583301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com