AppDividend
Latest Code Tutorials

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

1

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.

[capture clause] (parameters) -> return-type
{       
    // body
}

Usually, return type in the lambda expression is determined by the compiler automatically and we don’t need to specify that explicitly.

It is usually used to sort the vectors of elements in decreasing order. By default sort() function sorts in increasing order.

In the code mentioned below lambda functions have been used to sort a vector in decreasing order. First, a vector containing 5 elements is created. Then sort function is used in which the third parameter is actually a comparator that has been created using a lambda expression. Its return type is Boolean which returns true if the first parameter is greater than the second parameter that is if x>y it will return true.

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);

   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 ans = accumulate(a.begin(),a.end(),0,[](int i,int j){return i+j;});
    cout << "SUM: \n";
   
    cout << ans ;
    return 0;
}

See the following output.

 

C++ Lambda Function Tutorial

An empty capture clause [] have access limitation. Only those variable which is local to it can be accessed by it. One thing that is different with lambda functions compared to ordinary functions is that it can have access to external variables too. It is possible because of the capture clause.

[&] – Capture all external variables by reference.

[=] – Capture all external variables by value

[x,&y] – Capture x by value and y by reference.

Consider, capture by reference. To show this we can make some changes to a variable or data structure using lambda functions by passing it. And changes made will be visible even after its scope end.

In the code mentioned below first, a vector of 5 elements is created. Then with the help of lambda expression change, a new element is being pushed into the vector. auto automatically detects the type. [&] captures vector a by reference. Once, the new element is pushed back into this vector. It will be reflected after this scope. When a change(6) is called 6 is added to the vector and is reflected when the contents of the vector are printed.

#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);
   cout << "Before : ";
    for(int i=0;i<a.size();i++) cout << a[i] << " ";
    cout << "\n";
    auto change = [&](int x)
    {
        a.push_back(x);
    } ;
    change(6);
    cout << "After lambda function: ";
    for(int i=0;i<a.size();i++) cout << a[i] << " ";
    
   
    return 0;
}

See the following output.

 

Lambda Function Tutorial Example

Consider, now capture by value. To show this we can use some external variable inside the lambda function and output some result through it.

In the code mentioned below like in all cases a vector containing 5 elements is created. Then variable chk is created with value 3. Then to a variable sum lambda function is assigned. It uses the count_if predefined function. Its third parameter contains lambda expression which captures all external variables by value using [=]. It returns 1 when an element in the vector a is greater than equal to 3 otherwise it returns 0. After the execution sum contains the result.

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.

1 Comment
  1. ciclismo en Albacete says

    Hi there, its nice article regarding media print, we all understand media is a
    enormous source of data.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.