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

In C++, is there a way to call a function on each element of a vector, without using a loop running over all vector elements? Something similar to a 'map' in Python.


Solution 1:

Yes: std::for_each.

#include <algorithm> //std::for_each

void foo(int a) {
    std::cout << a << "\n";
}

std::vector<int> v;

...

std::for_each(v.begin(), v.end(), &foo);

Solution 2:

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.

Solution 3:

On C++ 11: You could use a lambda. For example:

std::vector<int> nums{3, 4, 2, 9, 15, 267};

std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });

ref: http://en.cppreference.com/w/cpp/algorithm/for_each