C ++ Map迭代器 [英] C++ Map Iterator

查看:56
本文介绍了C ++ Map迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序仅打印重复次数最多的单词.如果没有最多重复的单词要打印错误或无",我该怎么做?

The program just prints the most repeated word. How can I make it if there is no most repeated word to print error or "none"?

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

Input: 5 apple apple banana apple banana

输出:苹果

如果要说的话,我希望它显示

I want it to display if lets say

输入:苹果香蕉

输出:无"

#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 值.

Your use of std::max_element() is returning an iterator to the first element with the largest second value.

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

You can then use std::any_of() or std::none_of() to check if there are any remaining elements that have the same second value:

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

实时演示

这篇关于C ++ Map迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆