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 & range)
{
std::map<T, size_t> counts;
for (auto const & e : range) counts[e]++;

auto maxelem = std::max_element(
std::cbegin(counts), std::cend(counts),
[](auto const & e1, auto const & e2) {
return e1.second < e2.second;
});

std::vector<std::pair<T, size_t>> result;

std::copy_if(
std::begin(counts), std::end(counts),
std::back_inserter(result),
[maxelem](auto const & kvp) {
return kvp.second == maxelem->second;
});

return result;
}

The find_most_frequent() function can be used as follows:

int main()
{
auto range = std::vector<int>{1,1,3,5,8,13,3,5,8,8,5};
auto result = find_most_frequent(range);

for (auto const & e : result)
{
std::cout << e.first << " : " << e.second << std::endl;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset