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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iterator>
#include <vector>
// Returns the sum of all values in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type
sumRange( Iter first, Iter last)
{
std::iterator_traits<Iter>::value_type sum = std::iterator_traits<Iter>::value_type(0);
while ( first != last )
sum += *first++;
return sum;
}
// Returns the number of elements in an array with a pointer to the start and a pointer to the end+1
template <class Iter>
int sizeRange ( Iter first, Iter last)
{
return last - first;
}
// Returns the mean of all elements in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type
mean(Iter first, Iter last)
{
return sumRange(first, last) / sizeRange(first, last);
}
// Returns the mean of all elements in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type
median(Iter first, Iter last)
{
std::vector< std::iterator_traits<Iter>::value_type > arr( first, last );
std::sort( arr.begin(), arr.end() );
return arr.at( arr.size()/2 );
}
// Returns the first mode of all elements in the range [first, last)
// If no mode is found, 0 is returned.
template <class Iter>
typename std::iterator_traits<Iter>::value_type
mode(Iter first, Iter last)
{
typedef std::iterator_traits<Iter>::value_type type_t;
std::vector<type_t> arr (first, last);
std::sort(arr.begin(), arr.end() );
type_t output = type_t();
int final_frequency = 0;
int local_frequency = 0;
for (std::vector<type_t>::iterator it = arr.begin(); it != arr.end()-1; ++it)
{
if (*it == *(it+1)) local_frequency++;
else local_frequency = 0;
if (local_frequency > final_frequency)
{
final_frequency = local_frequency;
output = *it;
}
}
return output;
}
|