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 occured 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
We may reuse key or, value comparator objects as per requirements in place of comparator api, while fetching min/max/ranges over any STL iterator.
http://www.cplusplus.com/reference/map/multimap/key_comp/ http://www.cplusplus.com/reference/map/multimap/value_comp/
==
Example:
==
As someone accustomed to using boost libraries, an alternative to using the anonymous function proposed by Rob is the following implementation of std::max_element:
We can easily do this by using max_element() function.
Code Snippet :
you are almost there: simply add
currentMax = it->second;
aftermaax = it->first;
but using a map to locate the max is overkill: simply scan the vector and store the index where you find higher numbers: very similar to what you already wrote, just simpler.
You never changed
currentMax
in your code.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.
Here's a templated function based on Rob's excellent answer above.
Example:
Outputs: b=>2