typestar

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

  1. squared is sized up front so transform has somewhere to write.
  2. std::transform runs the squaring lambda over every element, filling squared in order.
  3. std::accumulate folds the squares into one int, starting from 0.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Algorithms, step 14 of 27 in Language basics.

← Previous Next →