Reputation: 1197
I want to combine these three features together:
into one example using C++11.
std::for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x) { std::cout<<x<<" ";});
How to convert that code to operate over std::array
?
Upvotes: 3
Views: 4962
Reputation: 73444
You want array::begin and array::end of the array, for the two first parameters of for_each()
, which will mark the start and end of the array.
Then the third parameter is a function, in your case a lambda function, like this:
std::for_each(myarray.begin(), myarray.end(), [](int x) { std::cout << x <<" "; });
PS: For a more generic approach, you could use std::begin()
and std::end()
, so that if the container changes (from std::array
to std::vector
for example), you can keep this code unchanged.
Upvotes: 6
Reputation: 4276
The answer is quite popular on the internet. I grabbed from std::array in action
Given:
std::array<int, 8> arr{1, 2, 3, 4, 5, 6, 7, 8};
Or even:
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
Use of for_each
and lambda
:
std::for_each(std::begin(arr), std::end(arr), [](int v){std::cout << v << " ";});
or even:
// calculate the sum of the array by using a global variable
int sum = 0;
std::for_each(std::begin(arr), std::end(arr), [&sum](int v) { sum += v; });
std::cout << "sum of array{1,2,3,4,5,6,7,8}: " << sum << std::endl;
Updated
Using std::begin()
and std::end()
instead of .begin()
and .end()
as suggested by @NathanOliver.
Upvotes: 0