What is a lambda expression in C++11?
What is a lambda expression in C++?
571
17-Aug-2023
Updated on 18-Aug-2023
Aryan Kumar
18-Aug-2023A lambda expression (also known as an anonymous function) in C++ is a short function that is defined inline. It is typically used to pass a function as an argument to another function or to create a closure.
Lambda expressions are defined using the
lambdakeyword. The syntax for a lambda expression is as follows:C++
capture: The capture list, which specifies the variables that are captured from the surrounding scope.parameters: The parameter list, which specifies the arguments to the function.mutable: Themutablekeyword, which specifies that the captured variables can be modified by the lambda expression.return_type: The return type of the function.body: The body of the function, which is the code that is executed when the function is called.The following is an example of a lambda expression that adds two numbers:
C++
In this code, the
add_two_numberslambda expression takes two numbers as its arguments and returns the sum of the two numbers. Theautokeyword is used to infer the return type of the function.Lambda expressions can be used in a variety of places in C++, including:
std::sort()function to sort a list of numbers in ascending order:C++
C++
C++