Learn C++ · lesson 29 of 61 · about 10 minutes
Project: Battle Statistics
Fight the boss: read the damage of each hit into a vector, and report the total, the best hit and the average.
What you'll learn
- Fill a vector from input
- Combine algorithms
- Print an average to one decimal place
The boss fight
Behind the last gate waits the boss. The damage of each hit is typed in, one number at a time, until a 0 ends the fight, and every hit goes into a std::vector<int>. Afterwards the adventure reports how many hits landed, their total with std::accumulate, the best one with std::max_element and the average to one decimal place. A total of 50 or more defeats the boss, and a fight with no hits has nothing to average.
The plan
1. Read scores until the input ends, pushing each into a vector
2. Average with accumulate
3. Median: sort a copy and take the middle (or the average of the two middles)
4. Count the passes with count_if and a small lambda
Score statistics
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
double median(std::vector<int> v) {
std::sort(v.begin(), v.end());
std::size_t n = v.size();
return n % 2 == 1 ? v[n / 2] : (v[n / 2 - 1] + v[n / 2]) / 2.0;
}
int main() {
std::vector<int> scores;
int s;
while (std::cin >> s) scores.push_back(s);
if (scores.empty()) {
std::cout << "No scores\n";
return 1;
}
double avg = std::accumulate(scores.begin(), scores.end(), 0.0) / scores.size();
auto passes = std::count_if(scores.begin(), scores.end(), [](int x) { return x >= 50; });
std::cout << std::fixed << std::setprecision(1);
std::cout << "Scores: " << scores.size() << "\n";
std::cout << "Average: " << avg << "\n";
std::cout << "Median: " << median(scores) << "\n";
std::cout << "Highest: " << *std::max_element(scores.begin(), scores.end()) << "\n";
std::cout << "Passed: " << passes << "/" << scores.size() << "\n";
}Output
Scores: 6
Average: 64.3
Median: 66.5
Highest: 90
Passed: 4/6Tip
[](int x) { return x >= 50; } is a lambda: a tiny unnamed function written right where it's needed. count_if calls it for each item.
Tip
max_element gives back an iterator, a position, not the number itself. Put * in front of it to get the item at that position.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.