Calling a function on every element of a C++ vector

You’ve already gotten several answers mentioning std::for_each.

While these respond to the question you’ve asked, I’d add that at least in my experience, std::for_each is about the least useful of the standard algorithms.

I use (for one example) std::transform, which is basically a[i] = f(b[i]); or result[i] = f(a[i], b[i]); much more frequently than std::for_each. Many people frequently use std::for_each to print elements of a collection; for that purpose, std::copy with an std::ostream_iterator as the destination works much better.

Leave a Comment