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?
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.
/* ... */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With