C++ Lambda Function Tutorial | Lambda expression in C++ Example

C++ Lambda Function Tutorial | Lambda expression in C++ Example

C++ Lambda Function Tutorial | Lambda expression in C++ Example is today’s topic. Lambda function or expression in c++ is very similar to inline functions that are not reused. It can be used for writing short snippets of code. Typically lambdas are used to encapsulate a few lines of code that are passed to algorithms or asynchronous methods.

Lambda expression in C++

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it is invoked or passed as an argument to a function.  A basic prototype of lambda expressions is following.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
   // Sample Code to show lambda expression
   vector<int> a;

   for(int i=0;i<5;i++)
     a.push_back(i+1);

   sort(a.begin(), a.end(), [](const int& x, const int& y) -> bool
    {
        return x > y;
    });
    cout << "Sorted List in decreasing order: n";
    for(int i=0;i<5;i++)
        cout << a[i] << " ";
    return 0;
}

See the output.

Lambda expression in C++

Another Example: Consider summing all the elements of a vector in a single variable. Lambda expression can be used to do this. In the code mentioned below first a vector is created containing 5 elements namely, 1 2 3 4 5. Then accumulate function is used whose fourth parameter contains lambda expression for summing the vector. ans variable holds the sum.

See the following code example.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
   // Sample Code to show lambda expression
   vector<int> a;

    for(int i=0;i<5;i++)
     a.push_back(i+1);
  
    int chk=3;
    
    int sum = count_if(a.begin(),a.end(),[=](int x)
                         {  return x>=chk; });
    cout << "Count of elements greater than equal to 3 in vector a : ";                     
    cout << sum;
   
    return 0;
}

See the following output.

Lambda expression in C++ Tutorial

Finally, C++ Lambda Function Tutorial | Lambda expression in C++ Example is over.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *