diff options
| author | Carlos Maiolino <[email protected]> | 2026-02-20 16:17:14 +0100 |
|---|---|---|
| committer | Carlos Maiolino <[email protected]> | 2026-02-20 16:17:14 +0100 |
| commit | 4ff0e42f65d8bba3d21bed53bfe1251d8db5c13f (patch) | |
| tree | 9ac61873e2676c3f392bd26063afeb16897c3902 /CPP/cpp_book/chap6/median.cpp | |
| parent | fd313dd5ad9ac067a31f2b1760b85bd305567131 (diff) | |
Diffstat (limited to 'CPP/cpp_book/chap6/median.cpp')
| -rw-r--r-- | CPP/cpp_book/chap6/median.cpp | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/CPP/cpp_book/chap6/median.cpp b/CPP/cpp_book/chap6/median.cpp new file mode 100644 index 0000000..e9932e8 --- /dev/null +++ b/CPP/cpp_book/chap6/median.cpp @@ -0,0 +1,21 @@ +#include <vector> +#include <algorithm> +#include <stdexcept> + +double median(std::vector<double> vec) +{ + std::vector<double>::size_type mid, size; + + size = vec.size(); + + if (size == 0) + throw std::domain_error("median of an empty vector"); + + sort(vec.begin(), vec.end()); + + mid = size / 2; + + return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2 + : vec[mid]; + +} |
