Get equal range with equal_range
#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;
}
}
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();
sort( v.begin(), v.end() );
vector<int>::iterator start = v.begin();
int mode_range = 0;
int mode_grade = 0;
pair<vector<int>::iterator,vector<int>::iterator> range;
// look for the largest range, which is the mode
while( start != v_end )
{
range = equal_range( start, v_end, *start );
if( range.second - range.first > mode_range ){
mode_range = range.second - range.first;
mode_grade = *start;
}
start = range.second;
}
cout << "Mode by method 2: " << mode_grade
<< "\n\nMinimum: " << v[0]
<< " Maximum: " << v[len-1]
<< " Median: " << v[len/2] << endl;
}
Related examples in the same category