fork download
  1. #include <stdexcept>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <iterator>
  5. #include <iostream>
  6. #include <type_traits>
  7.  
  8. template <typename iter_type>
  9. auto median(iter_type beg, iter_type end) -> typename std::remove_reference<decltype(*beg)>::type
  10. {
  11. if (beg == end)
  12. throw std::domain_error("median of empty container");
  13.  
  14. std::sort(beg, end);
  15.  
  16. std::size_t size = end - beg;
  17. std::size_t mid = size / 2;
  18.  
  19. if (size % 2)
  20. return *(beg + mid);
  21.  
  22. return (*(beg + mid - 1) + *(beg + mid)) / 2;
  23. }
  24.  
  25. int main()
  26. {
  27. int arr [] = { 9, 7, 5, 3, 1, 8, 6, 4, 2 };
  28. std::vector<double> v = { 9.1, 7.2, 5.3, 3.4, 1.5, 8.6, 6.7, 4.8, 2.9 };
  29.  
  30. std::cout << median(std::begin(arr), std::end(arr)) << '\n';
  31. std::cout << median(std::begin(v), std::end(v)) << '\n';
  32. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
5
5.3