Trying to find mode of a vector through a map

Im currently trying to find the mode of a vector through a map but am not sure how to do so besides the attempt ive made

void mode(vector<double>v)
{
map<double, int> map;

int num = 0;
int mode = 0;
for (int x = 0; v.size()-1; ++x)
{
if (v.at(x) == v.at(x + 1))
{
num += 1;
}
else if (v.at(x) != v.at(x + 1))
{
double i = v.at(x);
map.insert(i, num);
}
}

for (int x = 0; map.size()-1; ++x)
{
if (map.at(x) > map.at(x + 1))
{
mode = map.at(x);
}
}
cout << "Mode: " << mode << endl;
}
can you give me an example?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
double mode(vector<double> &v)
{
  map<double,int> mmap;
  pair<double,int> mode = pair<double,int>(0.0,0);

  for(int i = 0; i < v.size(); ++i)
  {
    double d = (v.at(i));
    map<double,int>::iterator f = mmap.find(d);
    if(f == mmap.end()) // number not found
    {
      mmap.insert(pair<double,int>(d,1));
    } else {
        f->second += 1;
        if(f->second > mode.second)
        {
          mode.first = f->first;
          mode.second = f->second;
        }
      }
    }
    cout << "Mode: " << mode.first << endl;
    return mode.first;
  }
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;
}


EDIT:
Don't forget to cater for multimode scenarios
Last edited on
Topic archived. No new replies allowed.