Basic question on lambda 'add' elements function

Feb 18, 2020 at 9:17pm
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#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;
}
Last edited on Feb 18, 2020 at 9:18pm
Feb 18, 2020 at 9:29pm
What do you mean by "lambda"?

C++11 has lambda closure syntax. Before C++11 you did need object for holding state (or, shock horror global).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector
#include <numeric>      // std::accumulate

struct myclass {           // function object type:
  int sum {};
  void operator() (int i) { sum += i; }
};

int main () {
  std::vector <int> myvalues { 2, 4, 6, 8, 10, 12 };

  std::cout << "function object:\n";
  myclass acc;
  acc = std::for_each( myvalues.begin(), myvalues.end(), acc );
  std::cout << acc.sum << '\n';

  std::cout << "lambda:\n";
  int sum {};
  std::for_each( myvalues.begin(), myvalues.end(), [&sum](int i){ sum += i; } );
  std::cout << sum << '\n';

  std::cout << "accumulate:\n";
  std::cout << std::accumulate( myvalues.begin(), myvalues.end(), 0 ) << '\n';
}
Last edited on Feb 18, 2020 at 9:33pm
Feb 18, 2020 at 9:30pm
One clarification: That's not a lambda, that's just passing a function pointer into the for_each algorithm.

Yes, the sum would get set to zero every time. std::accumulate would be a better fit here.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector <int> myvalues = { 2, 4, 6, 8, 10, 12 };
    int sum = std::accumulate(myvalues.begin(), myvalues.end(), 0);
    std::cout << sum << '\n';
}


See bottom of https://en.cppreference.com/w/cpp/algorithm/accumulate for an example of passing in a lambda to accumulate.

Edit: But I like keskiverto's example better if you're being forced to use for_each.
Last edited on Feb 18, 2020 at 9:33pm
Feb 18, 2020 at 10:32pm
Very good thanks.
Topic archived. No new replies allowed.