temp_stats.cpp in C++
Min, max, and mean over a dozen embedded readings, courtesy of std::ranges.
#include <algorithm>
#include <format>
#include <iostream>
#include <numeric>
#include <vector>
// temp_stats: min, max, and mean over a week of readings
int main() {
const std::vector<double> temps = {
61.2, 64.8, 70.1, 73.4, 71.9, 66.5, 62.3,
59.8, 63.1, 68.7, 72.2, 69.4,
};
auto [low, high] = std::ranges::minmax_element(temps);
double mean = std::accumulate(temps.begin(), temps.end(), 0.0)
/ temps.size();
auto above = std::ranges::count_if(
temps, [mean](double t) { return t > mean; });
std::cout << std::format("readings: {}\n", temps.size());
std::cout << std::format("min: {:5.1f} F\n", *low);
std::cout << std::format("max: {:5.1f} F\n", *high);
std::cout << std::format("mean: {:5.1f} F\n", mean);
std::cout << std::format("above the mean: {} of {}\n",
above, temps.size());
}
How it works
std::ranges::minmax_elementfinds both extremes in one pass; bindings name the iterators.std::accumulateseeded with0.0sums the readings for a floating-point mean.count_ifwith a[mean]capture reports how many readings sit above average.
Keywords and builtins used here
autoconstdoubleintmainreturn
The run, in numbers
- Lines
- 27
- Characters to type
- 795
- Tokens
- 242
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 171 seconds.
Step 3 of 3 in Encore, step 27 of 27 in Language basics.