fork download
#include 
#include 
#include 
#include 
#include 
#include 

template 
auto median(iter_type beg, iter_type end) -> typename std::remove_reference::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 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';
}
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
5
5.3