Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Nishtha Thakur

In C++11, the lambda was introduced. Lambdas are basically a part of code, that can be nested inside other function call statements. By combining lambda expressions with the auto keyword, they can be used later.

In C++14, these lambda expressions are improved. Here we can get the generalized lambda. For example, if we want to create a lambda, that can add integers, add numbers, also concatenate strings, then we have to use this generalized lambda.

Syntax of the lambda expression is looking like this:

[](auto x, auto y) { return x + y; }

Let us see one example to get the better idea.

Example

#include <iostream>
#include <string>
using namespace std;
main() {
   auto add = [](auto arg1, auto arg2) { //define generalized lambda
      return arg1 + arg2;
   };
   cout << "Sum of integers: " << add(5, 8) << endl;
   cout << "Sum of floats: " << add(2.75, 5.639) << endl;
   cout << "Concatenate Strings: " << add(string("Hello "), string("World")) << endl;
}

Output

Sum of integers: 13
Sum of floats: 8.389
Concatenate Strings: Hello World

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.