mode and map ? ? ?

I am struggling with a project right now and I was wondering if there was a quick way to find multiple modes in a map. So far I have a function that returns a vector of one or many modes depending on the map. I can't seem to wrap my head around how to test it->second against other seconds to find the one that occurs most often.

vector<double> mode(vector<double>& input)
{
map<double, double> tester;
vector<double> mode;

for (map<double, double>::size_type i = 0; i < input.size(); ++i)
{
++tester[input[i]];
}

for (map<double, double>::iterator it = tester.begin(); it != teseter.end(); ++it)
//if it->second is greater than or equal to other seconds, add to vector

return modes;
}
Last edited on
Flip your map into a std::multimap - that is, make the values the keys and vice versa, and the map will sort it out for you (literally).
Brute force.

Values of type int instead of double to side-step the complications involved in meeting C++ order-relation requirements with floating point values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <map>

std::vector<int> mode( const std::vector<int>& input )
{
    if( input.empty() ) return {} ;

    std::map< int, int > frequency_map ;
    for( int i : input ) ++frequency_map[i] ;

    std::map< int, std::vector<int>, std::greater<int> > reverse_frequency_map ;
    for( const auto& pair : frequency_map )
        reverse_frequency_map[pair.second].push_back(pair.first) ;

    return reverse_frequency_map.begin()->second ;
}

int main()
{
   for( int v : mode( { 7, 1, 2, 6, 3, 2, 7, 7, 6, 3, 4, 5, 2, 4, 3, 1, 6, 7, 2, 3 } ) )
       std::cout << v << ' ' ;
   std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/186d02a6381a5a70
Topic archived. No new replies allowed.