C/C++ Arena

Step 4 of 6

accumulate and transform

From <numeric>, std::accumulate folds a range into one value:

int sum = std::accumulate(v.begin(), v.end(), 0);
int prod = std::accumulate(v.begin(), v.end(), 1, [](int acc, int x) { return acc * x; });

std::transform applies a function to each element and writes the results somewhere:

std::vector<int> sq(v.size());
std::transform(v.begin(), v.end(), sq.begin(), [](int x) { return x * x; });

Your turn: write double average_damage(const std::vector<int>& hits) (0 for an empty vector) and std::vector<int> with_armor(const std::vector<int>& hits) that halves every hit (integer division). Use accumulate and transform.

Previous: find_if, count_if, any_of Next: Captures