48. The most frequent element in a range

In order to determine and return the most frequent element in a range you should do the following:

  • Count the appearances of each element in an std::map. The key is the element and the value is its number of appearances.
  • Determine the maximum element of the map using std::max_element(). The result is a map element, that is, a pair containing the element and its number of appearances.
  • Copy all map elements that have the value (appearance count) equal to the maximum element's value and return that as the final result.

An implementation of the steps described previously is shown in the following listing:

template <typename T>std::vector<std::pair<T, size_t>> find_most_frequent( std::vector<T> const ...

Get The Modern C++ Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.