Lambda Expressions in C++ 11 – Part 2 (Usage and Significance)

 In the previous article – Lambda Expressions in C++ 11 – Part 1 (Definition and Syntax), we discussed the meaning of lambda expressions and their syntax. Here, we shall discuss the usage of lambda expressions and the reasons why they are so significant.

Usage and significance of Lambda Expressions

As mentioned in the previous article, lambda expressions are, in a way, anonymous functions. A typical lambda has a parameter list, a body and can return values. It has a [] (known as the Capture Clause) in place of the function name, which contains the list of variables that are to be captured explicitly by the lambda (either by reference or by value).

A typical lambda looks like:-

[capture_clause] (parameter_list) {body of the lambda}

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

Now, why exactly do we need lambdas? What role do they play in our programs?

The main use of lambdas is as a replacement for function objects. A lambda has a compact syntax and does not require us to define a class. Hence, it results in a better code that is easier to write and less prone to errors as compared to function objects.

A lambda implicitly defines a function object class and then constructs a function object of that class type.

For example, to count the no. of even numbers in a vector using a lambda expression, you would write the following program :


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;                   // Create a vector object
    for (int i = 1; i <= 5; ++i)  // Add 5 members
    {
      v.push_back(i);
    }
    int num_even = 0; // num_even stores the total no. of even numbers in the vector

// The following code counts the no. of even numbers in the vector

    for_each(v.begin(), v.end(), [&num_even](int n) {
        cout << n;
        if (n % 2 == 0)
        {
             cout << " is even " << endl;
             ++num_even;
        }
        else
        {
             cout << " is odd " << endl;
        }
        return 0;
    });
// Now, display the total no. of even numbers in the vector
    cout << "This vector contains " << num_even << " even numbers " << endl;
getchar();
return 0;
}

Output of this lambda example

1 is odd
2 is even
3 is odd
4 is even
5 is odd
This vector contains 2 even numbers

Creating the same program using a function object instead of lambda expression


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

class func_class
{
  func_class& operator=(const func_class&);
  int& cnum_even;
public:
  explicit func_class(int& num_even) : cnum_even(num_even) {}
  void operator() (int n) const {
    cout << n;

    if (n % 2 == 0)
    {
      cout << " is even " << endl;
      ++cnum_even;
    }
    else
    {
      cout << " is odd " << endl;
    }
  }
};

int main()
{
  vector<int> v;
  for (int i = 1; i <= 5; ++i)
  {
    v.push_back (i);
  }

  int num_even = 0;

  for_each (v.begin(), v.end(), func_class (num_even));
    cout << " This vector has " << num_even << " even numbers. " << endl;
  getchar();
  return 0;
}

Output of this function object example

1 is odd
2 is even
3 is odd
4 is even
5 is odd
This vector has 2 even numbers.

As is obvious from the two programs shown above, lambda expressions have significant advantages over function objects.

 
These advantages are :
 
a) The use of a lambda expression results in a shorter code as compared to a function object.
b) There is no need to define a class while using a lambda expression, hence it is less complex than a function object.
c) In case of lambda, the “function body” is defined at the place where it is used. Therefore, finding and fixing errors is more convenient. Also, it is easy to make changes.
    On the other hand, in case of function objects, the “function” has to defined at a different location which makes it difficult to work with as compared to lambda expressions.
d) For short and simple programs, it is better to use lambda expressions since in these cases, it is not worthwhile to bother oneself with function objects.
 

However, there is one downside to using lambda expressions. If the functionality that is required in the program is complex, lambdas make it difficult to manage code properly. Therefore, if the required functionality is large and complex, it would be better to use function objects rather than lambdas.

Don’t forget to provide us your feedback in your comments.

(Visited 166 times, 1 visits today)

One comment

  • customized hoodies

    Hey! Someone in my Myspace group shared this website with us so I came to check it out.
    I’m definitely enjoying the information. I’m bookmarking and will
    be tweeting this to my followers! Exceptional blog and terrific style and design.

Leave a Reply

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