首页 > 解决方案 > 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");
}

标签: c++

解决方案


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


推荐阅读