lambda expression in C++11 and C++14?

Lamda expression in C++11 and C++14 is way of making anonymous function object. The below figure explains the basic syntax of Lamda expression. The starting syntax [] is known as Lamda introducer.

Lambda expression in C++11 and C++14A very simple example of Lambda expression

#include <iostream>
using namespace std;

int main() {
	auto func = [](int a) {
		cout <<"hello lamda:"<<a<<endl;
	};
	// call lamda
	func(5);
	return 0;
}

How to compile:
bosch@bosch-Inspiron-N5050:~$ g++ -std=c++11 lamda.cpp

A practical example of Lamda expression’s advantage

Let us write a old c++ code for displaying elements of a vector using for_each. To display the elements of a vector using for_each in old C++ wee need to write a trivial routine first.

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

using namespace std;

void display(int n) {
	cout << n << endl;
}
int main() {
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(5);
	v.push_back(4);
	v.push_back(8);
	for_each(v.begin(), v.end(), display);

	return 0;
}

We can use Lamda expression [](int n){cout<<n<<endl;} inside for_each inline to display the vector elements. The above code in c++ 11 can be written as

#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;

int main() {
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(5);
	v.push_back(4);
	v.push_back(8);
	for_each(v.begin(),v.end(),[](int n) {cout<<n<<endl;});

	return 0;
}

In all above example we have used empty capture list in lamda introducer []. we can capture list as value or reference. we can capture by value or reference inside [].

capture by value example:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
	int sum = 0;
	int divisor = 3;
	auto foo = [divisor](int sum) {sum = sum/divisor;
		cout << sum << endl;
	};
	foo(12); // it call lamda function foo with 12 and outputs 4
	return 0;
}

capture by reference by value :

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
	int sum = 0;
	const int &divisor = 3;
	auto foo = [=](int sum) {sum = sum/divisor;
		cout << sum << endl;
	};
	foo(12);
	return 0;
}

capture by reference by reference :

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
	int sum = 0;
	const int &divisor = 3;
	auto foo = [&](int sum) {sum = sum/divisor;
		cout << sum << endl;
	};
	foo(12);
	return 0;
}
  • []  empty capture list.
  • [=] capture any reference within lamda by value ( copy of divisor would happen).
  • [&] capture any reference variable within lamda by reference.

C++14 Generalized Lamda enhancement over C++11 Lamda

Follow the next link http://wikistack.com/c14-generalized-lamda-enhancement-over-c11-lamda/

References:

http://www-h.eng.cam.ac.uk/help/tpl/talks/C++11.html



Related Contents to follow