transform & accumulate in C++
Map then reduce, standard-library style: std::transform squares, std::accumulate sums.
#include <algorithm>
#include <numeric>
#include <vector>
int sum_of_squares(const std::vector<int>& values) {
std::vector<int> squared(values.size());
std::transform(values.begin(), values.end(), squared.begin(),
[](int x) { return x * x; });
return std::accumulate(squared.begin(), squared.end(), 0);
}
How it works
squaredis sized up front sotransformhas somewhere to write.std::transformruns the squaring lambda over every element, fillingsquaredin order.std::accumulatefolds the squares into oneint, starting from0.
Keywords and builtins used here
constintreturnsum_of_squares
The run, in numbers
- Lines
- 10
- Characters to type
- 305
- Tokens
- 100
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 92 seconds.
Step 2 of 3 in Algorithms, step 14 of 27 in Language basics.