In addition to other answers.
Use lambda when you need a simple predicate or comparator
Another useful pattern is to initialize const variables. Before lambdas, when initializing a variable became too complicated to fit a single expression, you had to either discard the constant or write a separate function that is used only once (which has other problems, for example, the need to pass arguments from the original scope).
Consider the following mute, extremely simplified example (suppose that initializing x cannot be rewritten as a single expression, because the if part if too complex):
void foo(int y) { int x = 42; if (y > 42) ++x;
Now with lambdas you can get rid of an additional function, passing parameters and at the same time save the constant:
void foo(int y) { const int x = [&]() { int x = 42; if (y > 42) ++x; return x; }(); // ^^ note: we call the lambda immediately // use x }
Of course, this still obeys the usual βrulesβ about whether we can write code in a line or whether we need to make a separate function. But this perfectly solves those (many!) Cases where the initialization code would be complex enough to refuse a constant, but not complex enough to justify a single function.
source share