Lambda expression

closed account (S879Nwbp)
The lambda expression is [capture](Argument list){function}

I was wondering why the capture variables are passed separately in the braces
instead of in the argument list. What criteria do you use to pass variables in
the capture list vs. the argument list?
Last edited on
I was wondering why the capture variables are passed separately in the braces
instead of in the argument list.
Because the values of captured variables in the body of the lambda are initialized just once, when the lambda is created, while the values of the parameters are re-initialized every time the lambda is called.

What criteria do you use to pass variables in the capture list vs. the argument list?
There's no criterion. You need to understand what a lambda is and what problem you're trying to solve with it. For example, does this usage make sense?
1
2
3
auto a = vector[0];
auto b = vector[1];
std::sort(vector.begin(), vector.end(), [&a, &b](const auto &, const auto &){ return a < b; });
Topic archived. No new replies allowed.