Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Algorithm to perform a non-modifying function on the elements of a sequence (on a std::vector, for example). Use std::transform to perform modifying functions on the elements of a sequence.
Prefer algorithms over hand-written loops [1-3]. View Exercise #9: No for-loops to learn how to remove hand-written loops .
Note: std::for_each is supposed to be non-modifying [1], but I use it for modifying my sequences anyway.
There are two kinds of examples below. The first uses std::for_each combined with simple functions.
The second piece of code shows the use of functors for more advanced functionality. It is advised to use the latter [3], but I will show the first as an example. There are also STL functors.
#include <algorith> |
#include <algorith> |
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.