We are going to build our own transform_if function which works by supplying std::accumulate with the right function objects:
- We need to include some headers, as always:
#include <iostream> #include <iterator> #include <numeric>
- First, we will implement a function called map. It accepts an input-transforming function as parameter and returns a function object, which works well together with std::accumulate:
template <typename T> auto map(T fn) {
- What we return is a function object that accepts a reduce function. When this object is called with such a reduce function, it returns another function object, which accepts an accumulator and an input parameter. It calls the reduce function on this accumulator and the ...