Hello, this should be simple, but I am running into the following problem:
I need to use a lambda function to add elements in a vector - OK.
Problem is, if I call the addElements function below, if I set a variable to hold the sum of 'value', it gets initialized to zero every time I call it.
Should I use a global variable for this ?(not very elegant I think).
Can you please confirm how you could handle this situation?
#include <iostream>
#include <vector>
#include <algorithm>
int addElements(int value) {
/*What would be the correct way to add elements here;
if I use:
int sum = 0;
sum = sum + value;
it does not work, since sum gets reinitialized and erased every time addElements is called...
*/
std::cout << value;
}
int main()
{
std::vector <int> myvalues = { 2, 4, 6, 8, 10, 12 };
std::for_each(myvalues.begin(), myvalues.end(), addElements);
return 0;
}