Finding the max value in a map
Solution 1:
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';
Solution 2:
This can be done in few lines, here's a full working snippet:
#include <iostream>
#include <algorithm>
#include <map>
int main() {
std::map<char,int> x = { { 'a',1 },{ 'b',2 },{'c',0} };
std::map<char,int>::iterator best
= std::max_element(x.begin(),x.end(),[] (const std::pair<char,int>& a, const std::pair<char,int>& b)->bool{ return a.second < b.second; } );
std::cout << best->first << " , " << best->second << "\n";
}
Solution 3:
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.