January 2018
Intermediate to advanced
374 pages
9h 53m
English
Although std::for_each is mainly used for applying a functor to a range of elements, it is quite similar to std::transform() although it only processes elements, like this:
auto peruvians = std::vector<std::string>{ "Mario", "Claudio", "Sofia", "Gaston", "Alberto"};
std::for_each(peruvians.begin(), peruvians.end(), [](std::string& s) {
s.resize(1);
});
// Peruvians is now {"M", "C", "S", "G", "A"}
It actually also returns the functor passed into it, which means it can be used like this:
auto result_func = std::for_each(
peruvians.begin(),
peruvians.end(), [all_names = std::string{}](const std::string& name) mutable {
all_names += name + " ";
return all_names;
}
);
auto all_names = result_func("");
// all_names is now "Mario ...