LearnFrenzy
Sign in Take a free test

Abstraction · Abstraction Programs · Question 6

Generic mean, median and mode with concepts in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write constrained templates mean, median and mode that work for any range of numbers (vector<int>, array of doubles), using a concept to describe the requirement.

Solution
main.cpp
#include <algorithm>
#include <array>
#include <concepts>
#include <format>
#include <iostream>
#include <map>
#include <ranges>
#include <vector>

template <typename R>
concept NumericRange = std::ranges::forward_range<R> && std::is_arithmetic_v<std::ranges::range_value_t<R>>;

template <NumericRange R>
double mean(const R& r) {
    double s = 0; std::size_t n = 0;
    for (auto x : r) { s += x; ++n; }
    return s / n;
}

template <NumericRange R>
double median(const R& r) {
    std::vector<double> v(std::ranges::begin(r), std::ranges::end(r));
    std::ranges::sort(v);
    std::size_t n = v.size();
    return n % 2 ? v[n / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
}

template <NumericRange R>
auto mode(const R& r) {
    std::map<std::ranges::range_value_t<R>, int> count;
    for (auto x : r) ++count[x];
    return std::ranges::max_element(count, {}, [](const auto& p) { return p.second; })->first;
}

int main() {
    std::vector<int> marks{72, 85, 85, 90, 64, 85, 72};
    std::array<double, 4> temps{31.5, 29.0, 33.5, 29.0};
    std::cout << std::format("{:.2f} {} {}\n", mean(marks), median(marks), mode(marks));
    std::cout << std::format("{:.2f} {} {}\n", mean(temps), median(temps), mode(temps));
    return 0;
}

Output Verified by compiling and running

79.00 85 85
30.75 30.25 29

The concept states the abstraction precisely: "a range of arithmetic values". Any container that fits works, and anything else is rejected with a clear message.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links