Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::for_each over std::array<> and apply lambda function on each element?

Tags:

c++

arrays

c++11

I want to combine these three features together:

  • std::for_each
  • std::array
  • lambda function

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 ?

like image 794
Amr Rady Avatar asked Jun 27 '26 04:06

Amr Rady


1 Answers

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.

like image 73
gsamaras Avatar answered Jun 29 '26 17:06

gsamaras