dbluesk dbluesk - 4 years ago 96
C++ Question

Applying a function to elements of a vector of arrays

I have a list of things which I encoded into a

. This is basically a list of points (x,y). I want to construct another list but now of the points (x,y^2).

I can do this with for loops, but what's the best way to achieve this using the STL algorithms? I was trying to do a
combined with lambdas, but I can't get there yet.

Answer Source

std::for_each applies a function to a range of elements, if you wan to applies a function to a range and stores the result in another range you should use std::transform. e.g.

std::transform(src.begin(), src.end(), std::back_inserter(dest),
               [](const std::array<double,2>& arr) { return std::array<double,2>{arr[0], arr[1] * arr[1]}; });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download