I am new to lambda expressions in C++ and have read about the different types of closures that can be provided but cannot seem to figure out the difference that this has on the outcome of the code. Here is an example
#include <iostream>
#include <array>
#include <algorithm>
using std::array;
using std::cout;
int main()
{
array<int,5> arr = {1,2,3,4,5};
std::for_each(arr.begin(), arr.end(), [](int& element) {element*=element;});
for(int element : arr)
{
cout << element << '\n';
}
}
I would have assumed that the difference between the closure types would be the way that the input variables were passed, but whether I put [], [&], or even [=] I get the same output(the square of each of the elements in the array. What difference is there between the different closure types and when should I use each of them?
Aucun commentaire:
Enregistrer un commentaire