Intermediate Project: A Small Library
Design and build one coherent, reusable statistics utility from scratch
Stats<T> class that collects numbers and computes statistics on them.
- plan a small library's public API before writing a line of it,
- wrap an STL container (
std::vector<T>) so RAII handles all memory for you, - make the class a template so it works for
int,doubleand more, - implement statistics with STL algorithms (
std::accumulate,std::min_element,std::sort), - apply const-correctness and pass objects by
constreference to avoid needless copies.
1. Plan first: what should the library do?
Think of a good library like a quality multi-tool. You do not carry ten separate gadgets; you carry one object whose buttons each do a clear job. Before writing code, we decide the public API — the set of operations a user can call — and keep everything else private.
Our target: a type Stats<T> that a user can fill with numbers, then ask for common statistics. The promised operations are:
add(value)andoperator+=— put a number in;count(),empty()— how many numbers so far;sum(),mean(),min(),max()— the basics;variance(),stddev(),median()— the spread.
The internal storage (a vector, an array, a file) is nobody's business but the class's. This separation — a clean surface over a hidden implementation — is called encapsulation, and it is the whole point of a library.
mean(), you can freely change how it is computed inside, but you must not change what it means outside.