Lambda expression
An introduction of Lambda expression in C++
Lambda expression is introduced in C++11. The purpose is to use a function without explicitly defining a function.
Syntax
1 | [ capture clause ] (parameters) -> return-type |
example 1
1 | int main() { |
example 2
Lambda expression can access external variables by []. There are 3 ways to capture variables.
- [&]: capture all external variables by reference.
- [=]: capture all external variables by value.
- [a, &b]: capture a by value and b by reference.
- []: an empty [] can access local variables.
1 | int main() { |
example 3
Pass lambda expressions to a function.
1 | int performOperation(int x, int y, std::function<int(int, int)> op) { |
example 4
Use lambda expression in a class.
1 | class Calculator { |
References
Lambda expression