Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a lambda an internal value that lasts as long as the lambda?

I'd like to have a variable I can modify inside a lambda without affecting the enclosing scope. Something that behaves like this:

std::vector vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
{
  auto sum = 0;
  std::for_each(vec.begin(), vec.end(), [sum](int value) mutable
  {
    sum += value;
    std::cout << "Sum is up to: " << sum << '/n';
  });
}

However, I'd like to be able to do it without declaring the sum variable outside the lambda. Something like this:

std::vector vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

std::for_each(vec.begin(), vec.end(), [auto sum = 0](int value) mutable
{
  sum += value;
  std::cout << "Sum is up to: " << sum << '/n';
});

So sum is only visible inside the lambda, not in the enclosing scope. Is it possible in C++11/14?

like image 829
Kian Avatar asked Dec 09 '25 06:12

Kian


1 Answers

C++14 introduces Generalized Lambda Capture that allows you to do what you want.

The capture will be deduced from the type of the init expression as if by auto.

[sum = 0] (int value) mutable {
    // 'sum' has been deduced to 'int' and initialized to '0' here.
    /* ... */
}
like image 142
Felix Glas Avatar answered Dec 10 '25 21:12

Felix Glas