Felix Dombek Felix Dombek - 24 days ago 10
C++ Question

C++ algorithm for applying a function to consecutive elements

Is there a simpler way to write this, e.g. by using an STL or boost algorithm?

std::vector<int> v { 0, 1, 2, 3 }; // any generic STL container
std::vector<int> result;
std::transform(v.begin(), v.end() - 1, // (0, 1, 2)
v.begin() + 1, // (1, 2, 3)
std::back_inserter(result),
[](int a, int b){ return a + b; }); // any binary function
// result == { 1, 3, 5 }

Answer

The binary version of std::transform can be used.

The std::adjacent_find/std::adjacent_difference algorithms can be abused.