Tuesday 4 June 2013

C++ 11 ( some important features ) Part4

Hello friends,
            Welcome you all in the C++ 11 Part4. In the Part3 we have discussed about range-based for statement and override virtual methods.

In this part we will learn about lambda functions.


Lambda function:-
            Anonymous functions are known as lambda function.     
Syntax:
            [capture] (parameters) -> return-type {body}

          body:                     This represent the function body.
return-type:             This can be omitted. If not present it's implied by the function return statements ( or void if it doesn't return any value) 
          parameters:             List of parameters as like named functions.
           

          Let’s have a look of the following code that demonstrates lambda function.
//author: shobhit upadhyaya
#include 
using namespace std;
int main()
{

int ret= [] () -> int {return 5; } ();
printf("ret = %d\n",ret);

// we can omit the return-type -> int, it is implied by the function return statement
int ret1= [] () {return 5;} ();
printf("ret1 = %d\n",ret1);

//parameter demonstration. 
int ret2= [] (int input) -> int { return (input * input * 5 ); } (5);
printf("ret2 = %d\n",ret2);

   return 0;
}
//

A lambda function can refer to identifiers declared outside the lambda function. The set of these variables is commonly called as closure. Closures are defined between square brackets [ and ] in the declaration of lambda expression. The mechanism allows these variables to be captured by value or by reference.

         capture: 
              Let's understand how to use the external variables inside the lambda function.

[]:        // no variables defined. We cannot use any external variables is the lambda function.
[ a, &b]:                     a is captured by value, b is captured by reference.
[&]:     any external variable is implicitly captured by reference if used.
[=]:     any external variable is implicitly captured by value if used.
[&, a]:            a is explicitly captured by value. Other variables will be captured by reference
[=, &b]:         b is explicitly captured by reference. Other variables will be captured by value

Following code gives the demonstration about how to use captures :-


//author: shobhit upadhyaya
#include 
#include 
using namespace std;

int main ()
{

 vector my_list (1,5);                       // five ints with value 1
 int sum = 0;
 
 // demonstration of captures
 /*
    lambda function:
      [&sum] (int x) { sum += x; }
      
      here we captured variable "sum" by reference ,so we can change the value of variable also.
 */
 printf("before, sum = %d\n",sum);
 
 for_each(begin(my_list), end(my_list), [&sum](int x) {
  sum += x;
});
 
  printf("after, sum = %d\n",sum);
  return 0;
}
//



Following code gives the demonstration of how we use STL without and with lambda function:-
//author: shobhit upadhyaya
#include 
#include 
#include 

using namespace std;

bool compare(int i,int j){return (i > j);}

using namespace std;
int main()
{
	int n = 10;

	vector v(n);
	//initialize the vector with values from 0 to 9
	for(int i=0; i < n; i++)
        {
          v[i] = i;
        }
	
	for(int i = 0; i < n; i++)
           printf("v[%d] == %d\n",i,v[i]);

	printf("\n");

	//sort the vector, with the help of compare function
	sort(v.begin(), v.end(), compare); // C++98 style
	
        for(int i = 0; i < n; i++)
	    printf("v[%d] == %d\n",i,v[i]);

	printf("\n");

        //sort the vector, with the help of lambda function
        sort(v.begin(),v.end(),[](int i, int j) -> bool{ return (i < j);}); //C++11 style
   
  
	for(int i = 0; i < n; i++)
           printf("v[%d] == %d\n",i,v[i]);

        printf("\n");

	return 0;
}


//





Give your comments and feedback.

Do not forgot to share J




No comments:

Post a Comment