Course Content
C++ Functions
C++ Functions
Lambda Functions
Lambda functions, or anonymous functions, are a feature that allows you to create small, unnamed functions inline in your code. They are particularly useful when you need a simple function for a short period of time and don't want to define a separate named function.
Lambda functions are useful for several reasons:
- Conciseness: Lambda functions allow you to write short and concise code. They are ideal for operations that can be expressed in a few lines.
- Local Scope: They can capture variables from the surrounding scope, allowing you to use variables from the parent function within the lambda.
- Flexibility: Lambdas can be passed as arguments to other functions, making them handy for functions like
std::for_each
,std::sort
, etc.
How to create a lambda function?
We can use the following syntax to create lambda function:
A capture clause in a lambda function allows you to specify which variables from the surrounding scope (outside the lambda function) can be accessed and used within the lambda function. There are 3 commonly types of capture clauses:
- Capture Nothing
[]
: The lambda function cannot access any variables from the surrounding scope. - Capture Specific Variables by Value
[var1, var2, ...]
: The lambda function can access specific variables from the surrounding scope by value. - Capture Specific Variables by Reference
[&var1, &var2, ...]
: The lambda function can access specific variables from the surrounding scope by reference.
main
#include <iostream> int main() { int multiplier = 2; // Lambda function capturing 'multiplier' by reference and with explicit return type (int) int result = [&multiplier](int num) -> int { return num * num * multiplier; }(5); // Invoking the lambda with argument 5 std::cout << "Result: " << result << std::endl; }
The function is constructed as follows:
- The lambda function captures
multiplier
variable by reference[&multiplier]
. - The return type
-> int
specifies that the lambda function returns an integer. - The lambda is immediately invoked with the argument
5
, and the result is stored in theresult
variable.
Thanks for your feedback!