62

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

cigien
  • 57,834
  • 11
  • 73
  • 112
Sh0gun
  • 871
  • 4
  • 10
  • 16

9 Answers9

120

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';
Chnossos
  • 9,971
  • 4
  • 28
  • 40
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Hi Rob, how to understand the function? Is it a overload of operator[]? [](const pair& p1, const pair& p2) { return p1.second < p2.second; } – thinkhy Jul 23 '14 at 23:14
  • http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B_.28since_C.2B.2B11.29 – Robᵩ Oct 04 '14 at 16:55
  • 1
    Shouldn't the int in pair<..> be const, i.e. pair? – thomasa88 Feb 05 '15 at 18:51
  • 1
    @thomasa88 yes it should and it would save much much unnecessary casting time. BTW if C++14 available just use auto instead. – Humam Helfawi Nov 13 '15 at 07:38
  • @HumamHelfawi `auto` already existed in C++11 and is specifically used above, but not for the `map` because you obviously can't deduce a type without an `rvalue`. Also, are there any sources documenting this "much unnecessary casting time"? – underscore_d Dec 06 '15 at 19:30
  • 1
    auto is included in c++ 11 but as lambda variable. it is c++ 14 see this http://stackoverflow.com/questions/32646362/why-auto-is-not-acceptable-as-lambda-parameter about casting time see the accepted answer here : http://stackoverflow.com/questions/32510183/can-the-use-of-c11s-auto-improve-performance – Humam Helfawi Dec 06 '15 at 22:16
  • #include include this lib – amin saffar Jan 29 '18 at 00:24
  • What is it's time complexity? – Mooncrater Feb 05 '20 at 14:42
26

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";
}
cigien
  • 57,834
  • 11
  • 73
  • 112
Janek_Kozicki
  • 736
  • 7
  • 9
  • 3
    why everyone uses std:: instead of using namespace? – user55924 Feb 06 '21 at 06:03
  • 9
    to avoid namespace pollution. Pollution can be a real hindrance in large projects. Even crashes due to linker confusing same class name coming from different namespaces: https://gitlab.com/yade-dev/trunk/-/issues/57 – Janek_Kozicki Feb 06 '21 at 18:52
  • 1
    With ranges: `std::ranges::max_element(x, [](std::pair a, std::pair b) { return a.second < b.second; })` – mheyman Nov 18 '21 at 14:56
22

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.

YXD
  • 31,741
  • 15
  • 75
  • 115
  • 3
    For a large map, it should be faster to use a map member function (maybe combined with binary search), std::map::upper_bound? – Erik Alapää Feb 10 '16 at 14:55
16

Here's a templated function based on Rob's excellent answer above.

template<typename KeyType, typename ValueType> 
std::pair<KeyType,ValueType> get_max( const std::map<KeyType,ValueType>& x ) {
  using pairtype=std::pair<KeyType,ValueType>; 
  return *std::max_element(x.begin(), x.end(), [] (const pairtype & p1, const pairtype & p2) {
        return p1.second < p2.second;
  }); 
}

Example:

std::map<char,int> x = { { 'a',1 },{ 'b',2 },{'c',0}}; 
auto max=get_max(x);
std::cout << max.first << "=>" << max.second << std::endl; 

Outputs: b=>2

daknowles
  • 1,426
  • 15
  • 19
5

We can easily do this by using max_element() function.

Code Snippet :


#include <bits/stdc++.h>
using namespace std;

bool compare(const pair<int, int>&a, const pair<int, int>&b)
{
   return a.second<b.second;
}

int main(int argc, char const *argv[])
{
   int n, key, maxn;
   map<int,int> mp;

   cin>>n;

   for (int i=0; i<n; i++)
   {
     cin>>key;
     mp[key]++;
   }

   maxn = max_element(mp.begin(), mp.end(), compare)->second;

   cout<<maxn<<endl;

   return 0;
 }
rashedcs
  • 3,588
  • 2
  • 39
  • 40
4

We may reuse key or, value comparator objects as per requirements in place of comparator api, while fetching min/max/ranges over any STL iterator.

http://www.cplusplus.com/reference/map/multimap/key_comp/ http://www.cplusplus.com/reference/map/multimap/value_comp/

==

Example:

// multimap::key_comp
#include <iostream>
#include <map>

int main ()
{
  std::multimap<char,int> mymultimap;

  std::multimap<char,int>::key_compare mycomp = mymultimap.key_comp();

  mymultimap.insert (std::make_pair('a',100));
  mymultimap.insert (std::make_pair('b',200));
  mymultimap.insert (std::make_pair('b',211));
  mymultimap.insert (std::make_pair('c',300));

  std::cout << "mymultimap contains:\n";

  char highest = mymultimap.rbegin()->first;     // key value of last element

  std::multimap<char,int>::iterator it = mymultimap.begin();
  do {
    std::cout << (*it).first << " => " << (*it).second << '\n';
  } while ( mycomp((*it++).first, highest) );

  std::cout << '\n';

  return 0;
}


Output:
mymultimap contains:
a => 100
b => 200
b => 211
c => 300

==

mav_2k
  • 171
  • 7
3

you are almost there: simply add currentMax = it->second; after maax = it->first;

but using a map to locate the max is overkill: simply scan the vector and store the index where you find higher numbers: very similar to what you already wrote, just simpler.

CapelliC
  • 59,646
  • 5
  • 47
  • 90
2

As someone accustomed to using Boost libraries, an alternative to using the anonymous function proposed by Rob is the following implementation of std::max_element:

std::map< int, unsigned >::const_iterator found = 
        std::max_element( map.begin(), map.end(),
                         ( boost::bind(&std::map< int, unsigned >::value_type::second, _1) < 
                           boost::bind(&std::map< int, unsigned >::value_type::second, _2 ) ) );
cigien
  • 57,834
  • 11
  • 73
  • 112
dr_g
  • 1,179
  • 7
  • 10
-3

Beter use inner comparator map::value_comp().

For example:

#include <algorithm>
...
auto max = std::max_element(freq.begin(), freq.end(), freq.value_comp());
std::cout << max->first << "=>" << max->second << std::endl

will output:

Key => Value
shed
  • 121
  • 1
  • 8
  • 7
    The code below will not work. auto p = std::max_element(freq.begin(), freq.end(), freq.value_comp()); Since > std::map::value_comp Returns a comparison object that can be used to > compare two elements to get whether the key of the first one goes > before the second. So p will point to the last element in map. – ivan2kh Mar 03 '14 at 23:11
  • 2
    That's the wrong comparator. See http://www.cplusplus.com/reference/map/map/value_comp/ – mmdanziger Dec 04 '14 at 13:57