1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
double mode(const vector<double> &myVec)
{
map<double, size_t > myMap;
for (const double &vecElm : myVec)
{
myMap[vecElm] = 0; // initialise map
}
for (const double &vecElm : myVec)
{
++myMap[vecElm]; // establish frequencies
}
map<double, size_t >::const_iterator ci = max_element(
myMap.begin(),
myMap.end(),
[](const pair<double, size_t >& p1, const pair<double, size_t >& p2)
{ return p1.second < p2.second; }
); // find highest frequency pair
return ci->first;
}
int main()
{
vector<double> myVec({2.3, 4.4, 5.6, 7.3, 4.4, 2.1, 5.3, 4.4, 5.6, 9.2, 12.13});
cout << "Mode = " << mode(myVec) << endl;
}
|