Search code examples
c++dictionaryvectormaxmode

Finding the max value in a map


I've been doing a basic program to find the max, min, median, variance, mode etc. of a vector. Everything went fine until I got to the mode.

The way I see it, I should be able to loop through the vector, and for each number that occurs I increment a key on the map. Finding the key with the highest value would then be the one that occurred the most. Comparing to other keys would tell me if it's a single multiple or no mode answer.

Here's the chunk of code that's been causing me so much trouble.

map<int,unsigned> frequencyCount;
// This is my attempt to increment the values
// of the map everytime one of the same numebers 
for(size_t i = 0; i < v.size(); ++i)
    frequencyCount[v[i]]++;

unsigned currentMax = 0;
unsigned checked = 0;
unsigned maax = 0;
for(auto it = frequencyCount.cbegin(); it != frequencyCount.cend(); ++it )
    //checked = it->second;
    if (it ->second > currentMax)
    {
        maax = it->first;
    }
    //if(it ->second > currentMax){
    //v = it->first

cout << " The highest value within the map is: " << maax << endl;

The entire program can be seen here. http://pastebin.com/MzPENmHp


Solution

  • You never changed currentMax in your code.

    map<int,unsigned> frequencyCount;
    for(size_t i = 0; i < v.size(); ++i)
        frequencyCount[v[i]]++;
    
    unsigned currentMax = 0;
    unsigned arg_max = 0;
    for(auto it = frequencyCount.cbegin(); it != frequencyCount.cend(); ++it ) }
        if (it ->second > currentMax) {
            arg_max = it->first;
            currentMax = it->second;
        }
    }
    cout << "Value " << arg_max << " occurs " << currentMax << " times " << endl;
    

    Another way to find the mode is to sort the vector and loop through it once, keeping track of the indices where the values change.