Calling a function on every element of a C++ vector
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);
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.
If you have C++11, there's an even shorter method: ranged-based for. Its purpose is exactly this.
std::vector<int> v {1,2,3,4,5};
for (int element : v)
std::cout << element; //prints 12345
You can also apply references and const to it as well, when appropriate, or use auto when the type is long.
std::vector<std::vector<int>> v {{1,2,3},{4,5,6}};
for (const auto &vec : v)
{
for (int element : vec)
cout << element;
cout << '\n';
}
Output:
123
456
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