C++ Lambda Functions
π§© C++ Lambda Functions
Lambda functions in C++ are anonymous (unnamed) functions that you can define inline.
They are especially useful for short operations, callbacks, and STL algorithms.
Introduced in C++11.
πΉ 1. Basic Syntax
-
capture β variables from outside the lambda
-
parameters β function parameters
-
return_type β optional (often auto-deduced)
πΉ 2. Simple Lambda Example
πΉ 3. Lambda with Parameters
πΉ 4. Lambda with Explicit Return Type
πΉ 5. Capture Variables (Very Important)
Capture by Value [=]
β Read-only copy inside lambda
Capture by Reference [&]
Capture Specific Variables
πΉ 6. Lambda in STL Algorithms (Very Common)
Example: for_each
Example: sort
πΉ 7. Lambda with mutable
Allows modification of captured-by-value variables.
πΉ 8. Lambda as Function Argument
πΉ 9. Lambda vs Normal Function
| Lambda | Normal Function |
|---|---|
| Inline & short | Separate definition |
| Can capture variables | Cannot capture |
| Common with STL | General purpose |
| Anonymous | Named |
β Common Mistakes
β Correct:
π Summary
-
Lambda = anonymous inline function
-
Syntax:
[capture](params){} -
Can capture variables by value or reference
-
Widely used with STL algorithms
-
Makes code concise and expressive
