Computing the Median 1 : pair « Map Multimap « C++






Computing the Median 1

  
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}

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

int main( )
{
    const int len = 15;
    const int a[len] = { 9, 2, 3, 3, 7, 5, 7, 7, 4, 10, 5, 6, 7, 4, 7 };

    vector<int> v( a, a + len );
    vector<int>::iterator v_end = v.end();
    print( v );
    
    map<int,int> frequency;
    for( vector<int>::iterator i = v.begin(); i != v_end;++i )
        ++frequency[*i];
    
    pair<int,int> mode_pair = *max_element( frequency.begin(),frequency.end(), second_less );
    
    cout << "Mode by method 1: " << mode_pair.first;
    
}
  
    
  








Related examples in the same category

1.Inserting pairs of object into map
2.print the maximum number of pairs that DateMap can hold
3.Use map to store the value of the month name and its day number
4.Iterating over the elements of the map and using the current pair option and second elements.
5.Put pairs to map with insert
6.Map for string key and integer value
7.for each basic
8.Sort a list of int and string pairs
9.Pass output message function to for_each function