Gosho
Gosho

Reputation: 51

C++ Map Iterator

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

Input: 5 apple apple banana apple banana

Output: apple

I want it to display if lets say

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

Upvotes: 1

Views: 332

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595782

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

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;

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

Upvotes: 1

Related Questions