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