In C++11, a lambda expression is a concise way to define anonymous functions, also known as lambda functions or closures. Lambda expressions allow you to create functions on-the-fly without having to define a separate function using the traditional function declaration syntax. They are particularly useful for short, localized functions that you need in a specific context.
A lambda expression has the following general syntax:
cpp
[capture_clause](parameter_list) -> return_type { function_body }
capture_clause
: Specifies which variables from the surrounding scope should be captured by the lambda.parameter_list
: Specifies the parameters that the lambda function takes.return_type
: Specifies the return type of the lambda function.function_body
: Contains the implementation of the lambda function.
Here's an example of a lambda expression in C++11:
cpp
#include <iostream>
int main() {
// Define a lambda expression that takes two integers and returns their sum
auto sum = [](int a, int b) -> int {
return a + b;
};
// Use the lambda function
int result = sum(5, 3);
std::cout << "Sum: " << result << std::endl;
return 0;
}
In this example, the lambda expression [](int a, int b) -> int { return a + b; }
defines an anonymous function that takes two integers and returns their sum. The auto
keyword is used to deduce the lambda's type.
Lambda expressions can also capture variables from their surrounding scope using the capture clause. For example:
cpp
#include <iostream>
int main() {
int factor = 2;
// Define a lambda expression that captures the 'factor' variable and multiplies it
auto multiply = [factor](int x) -> int {
return x * factor;
};
int result = multiply(5);
std::cout << "Result: " << result << std::endl;
return 0;
}
In this example, the lambda expression captures the factor
variable from the surrounding scope, allowing it to be used within the lambda function.
Lambda expressions are a powerful feature of C++11 and later versions that enable more concise and expressive code, especially when you need to create small, self-contained functions without the need for full function declarations.
Comments
Post a Comment