C++ Map Iterator

后端 未结 1 644
深忆病人
深忆病人 2021-01-24 09:39

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

相关标签:
1条回答
  • 2021-01-24 10:28

    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

    0 讨论(0)
提交回复
热议问题