#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';
}
I2luY2x1ZGUgPHN0ZGV4Y2VwdD4KI2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPHZlY3Rvcj4KI2luY2x1ZGUgPGl0ZXJhdG9yPgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDx0eXBlX3RyYWl0cz4KCnRlbXBsYXRlIDx0eXBlbmFtZSBpdGVyX3R5cGU+CmF1dG8gbWVkaWFuKGl0ZXJfdHlwZSBiZWcsIGl0ZXJfdHlwZSBlbmQpIC0+IHR5cGVuYW1lIHN0ZDo6cmVtb3ZlX3JlZmVyZW5jZTxkZWNsdHlwZSgqYmVnKT46OnR5cGUKewogICAgaWYgKGJlZyA9PSBlbmQpCiAgICAgICAgdGhyb3cgc3RkOjpkb21haW5fZXJyb3IoIm1lZGlhbiBvZiBlbXB0eSBjb250YWluZXIiKTsKICAgIAogICAgc3RkOjpzb3J0KGJlZywgZW5kKTsKCiAgICBzdGQ6OnNpemVfdCBzaXplID0gZW5kIC0gYmVnOwogICAgc3RkOjpzaXplX3QgbWlkID0gc2l6ZSAvIDI7CgogICAgaWYgKHNpemUgJSAyKQogICAgICAgIHJldHVybiAqKGJlZyArIG1pZCk7CgogICAgcmV0dXJuICgqKGJlZyArIG1pZCAtIDEpIC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