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
|
#include <stdexcept>
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <type_traits>
template <typename iter_type>
auto median(iter_type beg, iter_type end) -> typename std::remove_reference<decltype(*beg)>::type
{
if (beg == end)
throw std::domain_error("median of empty container");
std::sort(beg, end);
std::size_t size = end - beg;
std::size_t mid = size / 2;
if (size % 2)
return *(beg + mid);
return (*(beg + mid - 1) + *(beg + mid)) / 2;
}
int main()
{
int arr [] = { 9, 7, 5, 3, 1, 8, 6, 4, 2 };
std::vector<double> v = { 9.1, 7.2, 5.3, 3.4, 1.5, 8.6, 6.7, 4.8, 2.9 };
std::cout << median(std::begin(arr), std::end(arr)) << '\n';
std::cout << median(std::begin(v), std::end(v)) << '\n';
}
|