grade_report.cpp in C++
Averages and bests per student, printed as an aligned table with std::format.
#include <algorithm>
#include <format>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// grade_report: per-student averages in aligned columns
struct Student {
std::string name;
std::vector<int> scores;
};
int main() {
const std::vector<Student> roster = {
{"Ada", {92, 88, 95}},
{"Grace", {85, 91, 89}},
{"Alan", {78, 82, 80}},
{"Edsger", {90, 94, 97}},
};
std::cout << std::format("{:<8} {:>7} {:>5}\n",
"name", "average", "best");
std::cout << std::string(22, '-') << "\n";
double class_total = 0.0;
for (const auto &[name, scores] : roster) {
double avg = std::accumulate(scores.begin(), scores.end(), 0.0)
/ scores.size();
int best = *std::ranges::max_element(scores);
class_total += avg;
std::cout << std::format("{:<8} {:>7.1f} {:>5}\n",
name, avg, best);
}
std::cout << std::string(22, '-') << "\n";
std::cout << std::format("class average: {:.1f}\n",
class_total / roster.size());
}
How it works
- Each
Studentcarries a name and a vector of scores; the roster is brace-initialized. - Structured bindings unpack each student;
std::accumulateover0.0averages the scores. {:<8} {:>7.1f} {:>5}keeps every row in the same columns as the header.- The running
class_totaldivides out to a class average under the rule line.
Keywords and builtins used here
Studentautoconstdoubleforintmainstruct
The run, in numbers
- Lines
- 40
- Characters to type
- 925
- Tokens
- 306
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 230 seconds.
Step 2 of 3 in Encore, step 26 of 27 in Language basics.