Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 602
Sh0gun Avatar asked Feb 21 '12 01:02

Sh0gun


People also ask

How do you find the minimum element of a map?

The easy solution is to make it static : struct compare2nd { template <typename T> bool operator()(const T& pLhs, const T& pRhs) { return pLhs. second < pRhs. second; } }; min_element(mymap.

Can you sort a map in C++?

Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.


1 Answers

You can use std::max_element to find the highest map value (the following code requires C++11):

std::map<int, size_t> frequencyCount; using pair_type = decltype(frequencyCount)::value_type;  for (auto i : v)     frequencyCount[i]++;  auto pr = std::max_element (     std::begin(frequencyCount), std::end(frequencyCount),     [] (const pair_type & p1, const pair_type & p2) {         return p1.second < p2.second;     } ); std::cout << "A mode of the vector: " << pr->first << '\n'; 
like image 85
Robᵩ Avatar answered Sep 18 '22 07:09

Robᵩ