I have problem about lambda expression like this:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int sum(vector<int>& v){
int total = 0;
auto lambda = for_each(v.begin(), v.end(), [&total](int n){total = n;});
lambda; // lambda expression doesn't work.
for_each(v.begin(), v.end(), [&total](int n){total = n;}); // work same as I intended.
return total;
}
int main(void){
vector<int> v = {1, 2, 3, 4, 5};
cout << sum(v) << endl; // 30 (I think this should be 45.)
}
I thought that lambda;
could do same things like for_each
algorithm. Why lambda;
doesn't works?
CodePudding user response:
according to cppreference, the for_each(...)
call returns the UnaryFunction
which was passed to the function.
In this case, the for_each
returns the UnaryFunction
[&total](int n){total = n;}
a lambda(5)
would increase the total
value by 5.
A solution would be to put the for_each
call in a separate function - which is actually a "sum" function.
This is already done by the std:accumulate
function
std::accumulate(v.begin(), v.end(), 0);
CodePudding user response:
If do not take into account the side effect of accumulating the variable total this declaration
auto lambda = for_each(v.begin(), v.end(), [&total](int n){total = n;});
in fact is equivalent to
auto lambda = [&total](int n){total = n;};
So this statement
lambda; // lambda expression doesn't work.
does not make a sense.
So the declaration of the lambda expression is just redundant.
In fact you called the algorithm std::for_each two times in this declaration
auto lambda = for_each(v.begin(), v.end(), [&total](int n){total = n;});
and in this statement
for_each(v.begin(), v.end(), [&total](int n){total = n;});