Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- std::vector<int> Mode(std::vector<int> &myvector)
- {
- int vectorsize = myvector.size();
- int max = 0;
- std::vector<int> maxs;
- int counter = 1;
- std::sort(_vector.begin(), myvector.end());
- for (int i = 0; i < vectorsize - 1; i++)
- {
- int currentnum = myvector[i];
- if (currentnum == myvector[i + 1])
- {
- counter++;
- if (counter > vectorsize - i) break; //early exit when the mode found so far appears more than the number of elements still to be evaluated
- if (counter > max)
- {
- max = counter;
- if (maxs.size() > 0) maxs.clear();
- maxs.push_back(currentnum);
- }
- else if (counter == max)
- {
- bool alreadyin = false;
- for (int j = 0; j < maxs.size(); j++)
- {
- if (maxs[j] == currentnum)
- {
- alreadyin = true;
- break;
- }
- }
- if (alreadyin == false)
- maxs.push_back(currentnum);
- }
- }
- else counter = 1; //reset the counter
- }
- return (maxs.size() > 0) ? maxs : myvector; //if all elements appear only once, return the whole initial vector; otherwise return the the modes that were found
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement