A generalized (any uni-modal or multi-modal input sequence) version of essentially the same algorithm:
#include <map>
#include <iterator>
#include <algorithm>
#include <iostream>
// C++1x
template< typename INPUT_ITERATOR, typename OUTPUT_ITERATOR >
void copy_modal_values( INPUT_ITERATOR begin, INPUT_ITERATOR end, // input sequence
OUTPUT_ITERATOR result ) // modes to be placed in this sequence
{
typedef typename std::iterator_traits<INPUT_ITERATOR>::value_type key_type ;
std::map< key_type, int> frequency_map ;
while( begin != end ) ++frequency_map[*begin++] ;
int max_freq = 0 ;
for( auto iter = frequency_map.begin() ; iter != frequency_map.end() ; ++iter )
if( iter->second > max_freq ) max_freq = iter->second ;
for( auto iter = frequency_map.begin() ; iter != frequency_map.end() ; ++iter )
if( iter->second == max_freq ) *result++ = iter->first ;
}
// simple test driver
int main()
{
const int a[] = { 1, 2, 6, 7, 6, 2, 8, 8, 6, 8, 2, 9 } ;
enum { N = sizeof(a)/sizeof(*a) } ;
std::cout << "modes of [ " ;
std::for_each( a, a+N, [](int i ) { std::cout << i << ' ' ; } ) ;
std::cout << "] are [ " ;
copy_modal_values( a, a+N, std::ostream_iterator<int>( std::cout, " " ) ) ;
std::cout << "]\n" ;
}