LearnFrenzy
Sign in Take a free test

Templates · Template Programs · Question 9

Running statistics class template for any number type in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write Stats<T> (constrained to arithmetic T) that accepts values one at a time and reports count, min, max and mean; use it for int marks and double temperatures.

Solution
main.cpp
#include <format>
#include <iostream>
#include <limits>
#include <type_traits>

template <typename T>
    requires std::is_arithmetic_v<T>
class Stats {
    std::size_t n_ = 0;
    T min_ = std::numeric_limits<T>::max();
    T max_ = std::numeric_limits<T>::lowest();
    double sum_ = 0;
public:
    Stats& add(T x) {
        ++n_; sum_ += x;
        if (x < min_) min_ = x;
        if (x > max_) max_ = x;
        return *this;
    }
    template <typename... Ts>
    Stats& add_all(Ts... xs) { (add(static_cast<T>(xs)), ...); return *this; }
    std::string report() const {
        return std::format("n={} min={} max={} mean={:.2f}", n_, min_, max_, n_ ? sum_ / n_ : 0.0);
    }
};

int main() {
    Stats<int> marks;
    marks.add(72).add(91).add_all(64, 88, 79);
    Stats<double> temps;
    temps.add_all(31.5, 29.25, 33.0, 30.75);
    std::cout << marks.report() << '\n' << temps.report() << '\n';
    return 0;
}

Output Verified by compiling and running

n=5 min=64 max=91 mean=78.80
n=4 min=29.25 max=33 mean=31.12

numeric_limits<T> gives the right starting values for each type (lowest() rather than min(), which is the smallest positive value for double). The variadic add_all uses a comma fold.

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