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?
>Solution :
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);