C++Lambda Expressions
ConcepttheLambda ExpressionsinC++
Starting with the release c++11
, a new method has been added that can be used to reduce code size when defining new functions.
The new method that we will learn in this lesson to define functions is calledLambda ExpressionsorClosuresorLiterals FunctionorLambdasJust.
The working form of the definition ofLambda Expression in C++
[captures] (parameters) -> returnTypesDeclaration { lambdaStatements; };
Place of the word captures
You can pass the values or addresses of variables defined outside the function only so that you can access and manipulate them from inside the function, noting that two empty boxes must be placed []
if you do not want to put parameters in it.
The place of the word parameters
You can put parameters for the function, noting that you can not put the parentheses ()
at all if you do not want to put parameters in it.
word place returnTypesDeclaration
We pass the type of value that the function will return when it is executed. Here the compiler can most likely know what the function will return automatically if it contains only one command, but it is always better to specify the return type yourself.
In place of the word lambdaStatements
we put the commands that we want to be executed when the function is called.
Basics of dealing withLambda ExpressionsinC++
The normal function we give it a name when we define it and later when we want to implement it we call it by writing its name and this is how the compiler will understand that we want to implement it.
The function that is defined by the . methodLambda ExpressionsWe do not give it a name, but we assign it to a variable of the same type in order to invoke it through it or make the type of the variable that will refer to it auto
so that the compiler can set the appropriate type for this variable.
In the following example, we have defined a function that does not have any parameters in a methodLambda Expressions.
When we define it, we assign it to a variable with its name lambda
and type auto
so that we can call it later. Finally, we called the function by the variable lambda
and notice how we put parentheses after the variable name exactly as we call the regular function.
#include <iostream> using namespace std; int main() { // equals it so that we can later call it lambda and then we define a variable named Lambda Expression here we define a function with a method auto lambda = [] { cout << "My first lambda expression"; }; // and notice that we put parentheses after it as if we were calling a regular lambda function here we called the function to which the variable refers lambda(); return 0; }
• We will get the following result when running.
My first lambda expression
The function we defined in the previous example could have been defined in several different forms and get exactly the same result.
Below we are going to show you 5 different ways that could have been used to define the following function.
auto lambda = [] { cout << "My first lambda expression"; };
Method 1: You could have added the parentheses for the parameters and left them blank as follows.
auto lambda = []() { cout << "My first lambda expression"; };
Method 2: You could put the word void
in parentheses, which means that there are no parameters as well.
auto lambda = [](void) { cout << "My first lambda expression"; };
The third method: You could specify that the function does not return a value after it is executed, i.e. mention that its type void
and here it is necessary to put the parentheses of the parameters before it as follows.
auto lambda = []() void { cout << "My first lambda expression"; };
The fourth method: You could put the parentheses of the parameters and the word inside them, in void
addition to mentioning that the function is also of its type void
as follows.
auto lambda = [](void) void { cout << "My first lambda expression"; };
Comprehensive examples of ways to defineLambda ExpressionsinC++
first example
In the following example, you will learn how to set parameters for a function defined by a methodLambda ExpressionsIn addition to being summoned.
In the following example, we have defined a function with the method .Lambda ExpressionsWith two parameters in itint
.
When we define it, we assign it to a variable with its name lambda
and type auto
so that we can call it later.
The task of this function is to add the two numbers that we pass to it and then print the result.
Finally, we called the function by the variable lambda
and notice how we put parentheses after the variable name exactly as we call the regular function.
#include <iostream> using namespace std; int main() { // Its task is to print the product of the two numbers we pass in void and its type int contains two parameters of type Lambda Expression. Here we have defined // equals the function we have defined so that later we can call it lambda when called, and we also declared a variable named auto lambda = [](int a, int b) void { cout << a << " + " << b << " = " << a + b; }; // b and a with many passed 3 and 5 have the place of the two parameters lambda here we called the function that the variable points to lambda(3, 5); return 0; }
• We will get the following result when running.
3 + 5 = 8
second example
In the following example, you will learn how to define a function with a methodLambda ExpressionsReturns a value in addition to being called.
In the following example, we have defined a function with the method .Lambda ExpressionsWith two parameters in itint
.
When we define it, we assign it to a variable with its name lambda
and type auto
so that we can call it later.
The task of this function is to add the two numbers we pass to it and then return the result.
Finally, we called the function by the variable lambda
and notice how we put parentheses after the variable name exactly as we call the regular function.
#include <iostream> using namespace std; int main() { // also an int specifying that it returns a value of type int containing two parameters of type Lambda Expression Here we have defined // equals the function that we have defined so that we can later call it lambda as we have defined a variable named auto lambda = [](int a, int b) int { return a + b; }; // with many passing 3 and 5 have lambda here we have called the function to which the variable is pointing // and printing the sum returned by the function will be displayed as b and a in place of the two parameters cout << "3 + 5 = " << lambda(3, 5); return 0; }
• We will get the following result when running.
3 + 5 = 8
third example
In the following example, you will learn how to define a function with a methodLambda ExpressionsWith external variables passed to it as well as being called.
In the following example, we have defined two variables with their name a
and b
initial values.
Then we define a function with a methodLambda ExpressionsWith the two variables passed a
and b
have as they are.
When we define it, we assign it to a variable with its name lambda
and type auto
so that we can call it later.
The task of this function is to add the two numbers we pass to it and then return the result.
#include <iostream> using namespace std; int main() { int a = 3; int b = 5; // its int, and specifying that it returns a value of type b and a with the two variables passed in Lambda Expression Here we have defined // equals the function that we have defined so that we can later call it lambda as we have defined a variable named auto lambda = [a, b]() int { return a + b; }; // and then we print the output b and a to return the sum of the two numbers in the lambda variables here we called the function to which the variable refers cout << a << " + " << b << " = " << lambda(); return 0; }
• We will get the following result when running.
3 + 5 = 8
Technical information
Pass the variable as is to a function defined by a methodLambda ExpressionsIt makes you able to only read their values without being able to modify them.
If you want to update the values of the variables that are passed to the function, you must pass the addresses of the variables to it, not just their names.
Fourth example
In the following example, you will learn how to define a function with a methodLambda Expressionswith addresses of external variables being passed to them as well as being called.
In the following example, we have defined two variables with their name a
and b
initial values.
Then we define a function with a methodLambda ExpressionsPassing the addresses of the variables a
and b
them.
When we define it, we assign it to a variable with its name lambda
and type auto
so that we can call it later.
The task of this function is to add the two numbers we pass to it and then return the result.
#include <iostream> using namespace std; int main() { int a = 3; int b = 5; // its int, and specifying that it returns a value of type b and a with the addresses of the two variables being passed in Lambda Expression Here we have defined // equals the function that we have defined so that we can later call it lambda as we have defined a variable named auto lambda = [&a, &b]() int { return a + b; }; // and then we print the output b and a to return the sum of the two numbers in the lambda variables here we called the function to which the variable refers cout << a << " + " << b << " = " << lambda(); return 0; }
• We will get the following result when running.
3 + 5 = 8
Fifth example
The following example is very important because it is considered the main goal of creating a styleLambda ExpressionsIt is usually used for this very purpose, since from it you will learn how to pass a function as a parameter to another function the moment it is defined.
Define functions in a styleLambda ExpressionsIt is usually used when using a function that contains a parameter that is another function.
In dynamic containers lesson(ST)Specifically, when we explained how to deal with the class , forward_list
we used a function called remove_if()
it, and we said that this function must be passed to another function when it is called in order to determine how the elements will be deleted from the object.
Note: You should review this lesson carefully and read all the examples in it in order to understand what will be explained now.
In that lesson, specifically in the fifth example, we define the function shouldBeRemoved()
and then pass it to the function remove_if()
as follows.
// shouldBeRemoved() This is how we defined the function bool shouldBeRemoved(const int& value) { if (value > 3) { return true; } return false; } .. .. // remove_if() and this is how we pass it to the function myList.remove_if(shouldBeRemoved);
So what we did at that time was we defined a regular function named shouldBeRemoved()
and passed it to the functionLambda ExpressionsBut now we will repeat the same previous code and define the same previous function in a styleLambda ExpressionsWith it passed directly to the function remove_if()
as follows.
myList.remove_if( [](const int& value) { if (value > 3) { return true; } return false; });
Now if we were to repeat the same as the fifth example focusing only on passingLambda ExpressionsFor the function remove_if()
, the code will be as follows.
#include <iostream> #include <forward_list> using namespace std; int main() { // In addition, we have added several values in which int can contain elements of type forward_list here we have defined an object of the class forward_list<int> myList = {1, 3, 2, 4, 2, 5, 1, 5}; // remove_if() to remove all elements that meet the condition we passed in parentheses of the myList function from the remove_if() object here we called the function // Lambda Expression Note that we pass the same function that we passed in the example before, but with the remove_if() method between the parentheses of the function myList.remove_if( [](const int& value) { // to tell the compiler that the element should be deleted from the object that called it true here we said that any element with a value greater than 3 will return the function if (value > 3) { return true; } // tells the compiler that the element should not be deleted from the object that called it false if the element value is not greater than 3 the value will be returned return false; }); cout << "List values = "; // from the first to the last myList element here we create a loop that every cycle prints the value of a new element from the elements in the object for (auto it = myList.begin(); it != myList.end(); ++it) { cout << *it << ""; } return 0; }
• We will get the following result when running.
List values = 1 3 2 2 1