Lambda Expression in C++

So in this tutorial, we are going to learn and implement Lambda Expression in C++.

So while writing programs in C++, you may have come to one point where you wished that just like normal variables if you can pass functions as a parameter as well.

This can be achieved using “Lambda expression”.

  • However, the concept “Lambda expression” were introduced in C++ 11, allowing us to write inline functions in our program.
  • Moreover, these expressions can be used for writing a few lines of code that are not worth naming and are not going to be reuse.
  • A lambda expression can be written as,
[ capture-clause ] (parameters) mutable throw -> return_type
{ 
    //lambda body 
}
  • Optional Parts: “parameters”, “mutable”, “throw” & “return_type”
  • We don’t need to specify the return_type in a lambda expression as the compiler decides that most of the time.

Let’s look at a code snippet and understand the concept more clearly,

 #include <bits/stdc++.h> 
using namespace std; 

void show(vector<int> a) 
{ 
  // lambda expression to print vector 
  for_each(a.begin(), a.end(), [](int i) 
  { 
    cout << i << " "; 
  }); 
  cout << endl; 
} 

int main() 
{ 
  vector<int> a {4, 1, 6, 5, 3, 6, 1, 7}; 

  cout<<"Elements of vector 'a' are: ";
  show(a); 

  vector<int>:: iterator p = find_if(a.begin(), a.end(), [](int i) 
  
    { return i > 4; } //This lambda expression will return the location of first element
                      //greater than 4.
  
  );
 
  cout << "\nFirst number greater than 4 is : " << *p << endl; 

  sort(a.begin(), a.end(), [](const int& a, const int& b) -> bool
  
   { return a > b; } //sort function in C++ usually sorts in increasing order
                     //but using lambda expression we can sort it in decreasing order
                     //Here we have explicitly provided the return type "bool"

  );
  cout<<"\nElements of vector 'a' after sorting : ";
  show(a);
 
  p = unique(a.begin(), a.end(), [](int a, int b) 
  { 
    return a == b; // lambda expression for removing duplicate element
	          // (after sorting all duplicate comes together)
  }); 


  cout<<"\nUnique elements in vector 'a' are: "; 
  a.resize(distance(a.begin(), p)); 
  show(a); 
 
  int arr[] = {1, 2, 3, 4, 5}; 

  // accumulate function accumulate the container based on
  // function provided as third argument
  int fact = accumulate(arr, arr + 5, 1, [](int p, int q) 
  { 	
    return p * q; 
  }); 

  cout << "\nFactorial of 5 is : " << fact << endl; 

} 

So the output for the above program is,

Elements of vector 'a' are: 4 1 6 5 3 6 1 7

First number greater than 4 is : 6

Elements of vector 'a' after sorting : 7 6 6 5 4 3 1 1

Unique elements in vector 'a' are: 7 6 5 4 3 1

Factorial of 5 is : 120

(Note: Lambda expression with an empty capture clause [ ] can have access only to those variables which are local to it.)

Ways of Capturing Variables

  • In addition to this, just like a normal function, we can also have access to variables through enclosing scope.
  • The 3 ways by which we can access the external variable is to capture by,

->Value

->Reference or

->Both(Value and Reference)

  • So in the capture clause, we need to specify the type of accessing the variables similarly as we do in normal functions.

The syntax for this is shown below,

[&]: All external variables are captured by reference
[=]: All external variables are captured by value
[i, &j]: capture ‘i’ by value and ‘j’ by reference

For instance, if there are two variables say var1 and var2 which are accessed by a lambda expression “by reference” and “by value” respectively then equivalent capture clauses are as following:

[&var1, var2]
[var2, &var1]
[&, var2]
[var2, &]
[=, &var1]
[&var1, =]
  • (Note:- Lambda expression work’s only on C++ 11 and greater versions.)

So thanks for reading this tutorial and for any queries regarding the post comment down below.

Also read:

Leave a Reply

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