Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why output is different though expressions are same in lambda expression?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading