C++

Lambdas in C++

“With the help of illustrations, we will discuss C++ lambda functions in this article.

We can define anonymous method instances in C++ Lambda statements, which could then be utilized inline or supplied as parameters. Since we will not have to override the operator in a different class or structure, they are much more effective.”

Syntax of Lambda Function

The lambda introducer [] in this case represents the beginning of the lambda statement, and the argument list [] is identical to the () operator of a standard method.

Example no 1

In this instance, we’ve compiled a basic C++ lambda statement code that displays the name of Germany.

#include <iostream>
using namespace std;

int main() {

  auto country = []() {
    cout << "Germany";
  };
  country();

  return 0;
}

We will include the required header file <iostream> and standard namespace at the commencement of the program. Then we start the coding inside the main() function. We will create a lambda method by using the keyword “auto”. We will assign the variable “country” to the lambda method. Then, by using the country variable and the () operator, we have invoked the lambda method. Further, we have used the “cout” statement to print the name of the country. Let’s invoke the lambda function. In the end, we just enter the “return 0” command.

Example no 2

Lambda statements would also require arguments, just like a standard method. Here, we have constructed a lambda method that displays the sum of two numbers. The lambda method was then invoked with two integer parameters.

#include <iostream>
using namespace std;

int main() {

  auto add = [] (int x, int y) {
   cout << "Sum of two numbers = " << x + y;
  };

  add(250, 69);
  return 0;
}

We start the program by including the library <iostream>. Then we utilize the standard namespace. We will call the main() function. Now we create a lambda function of “add”. Here we pass two variables as the arguments of this function. The “cout” statement is being used to print the sum of these specified values. In the next step, we call the lambda method. This method contains two integers as its parameters. Lastly, we have to enter the ‘return 0’ command.

Example no 3

Here, we’ve constructed a lambda method to determine both the average of 2 numbers and the sum of 2 numbers. By providing “s” as the third parameter to main(), we may calculate the sum of two numbers. Even if the lambda provides a random number in this case, double type conversion is made directly. The average is then calculated by using a different string as the parameter:

#include<iostream>
using namespace std;

int main() {
  auto op = []  (int i, int j,  string op) -> double {
    if (op == "s") {
      return i + j;
    }
    else {
      return (i + j) / 2.0;
    }
  };

  int n_1 = 11;
  int n_2 = 21;
  auto s = op(n_1, n_2, "s");
  cout << "Sum of two numbers= " << s << endl;

  auto average = op(n_1, n_2, "average");
  cout << "Average = " << average;

  return 0;
}

We are going to integrate the module <iostream> for input and output functionalities. The lambda function will have been created in the next step. Here the lambda function “op” is applied by its explicit return type “double”. This lambda function returns the sum or the average of the values. We will provide two variables having an integer data type and a string as the parameters of the lambda function.

Further, we have applied the “if” statement. If the value of the “op” variable is equal to the sum of the numbers. Then it returns the value by adding both numbers. Otherwise, it returns the average by dividing the sum of the numbers by 2. We initialize two new variables and set their values. We use the “cout” statement to show the sum. Now to obtain the average of the required values, we apply the lambda function “average”. We have given the integers as arguments to this lambda function. The “cout” statement will be used to show the average value. To terminate the code, we will employ “return 0”.

Example no 4

By default, lambda methods are unable to retrieve the indented function’s variables. We utilize the capture statement to obtain access to those attributes. This is identical to invoking a method by value. When the lambda is constructed in this case, the original value is taken. The variable included within the lambda argument will only be read at this point; it cannot be changed.

The following is an example of a simple lambda function with capture by value:

Thus, the lambda function has accessibility to the int “n” variable due to initial “s”. As int “n” will not be retrieved from the lambda body unless we eliminate it from the capture clause, then we will find an error.

#include<iostream>
using namespace std;

int main() {

  int initial_s = 389;

  auto add_to_s = [initial_s] (int n) {
    return initial_s + n;
  };
  int final_s = add_to_s(45);
  cout << "389 + 45 = " << final_s;
  return 0;
}

First of all, for input and output processes, the header file will be included. Along with this standard namespace will be added. We now call the main() function. Within the body of the main() function, we initialize a variable “initial_s”. We specify the value “389” to this variable. Then we capture the variable “initial_s” by its value. Hence we have been using the lambda function of “add_to_s”. We will pass two variables as the parameter to the lambda function.

The first parameter shows the variable “initial_s”, and the second parameter shows the variable “n”. The sum will be kept in a variable “final_s”. The data type of this variable is an integer. Before adding the “return 0” command, we have to utilize the “cout” statement. The “cout” statement shows the resultant value.

Conclusion

The C++ lambda statements guide has concluded. The new notion in C++, inline execution, is highly useful whenever we need to run a short piece of code. Additionally, lambdas may be declared generic and applied to any sort of data. This article has four separate instances that we’ve fully implemented. The lambda function is used without any arguments in the first instance. We provide the lambda method with a variety of parameters in the second example. Similarly, we have utilized the lambda method’s explicit return type in the third scenario. The Lambda Function and the Capture Clause have been used in the last one.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.