New C++0x features – part 1 [ lambda ]

Today, I would like to discuss a new feature in c++0x. This would be available in your microsoft visual studio 2010 versions ( i.e VC10)
Before you used to write this:


// for_each example
#include
#include
#include
using namespace std;
void myfunction (int i) {
  cout << " " << i;
}
struct myclass {
  void operator() (int i) {cout << " " << i;}
} myobject;
int main () {
  vector myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);
  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);
  // or:
  cout << "nmyvector contains:";
  for_each (myvector.begin(), myvector.end(), myobject);
  cout << endl;
  return 0;
}

Notice that you have a separate function or struct called myobject. But in the newer version of c++ you really can put the whole function inside this lambda function.
Basically expand the whole stuff like this as shown below:

int main () {
	vector myvector;
	myvector.push_back(10);
	myvector.push_back(20);
	myvector.push_back(30);
	cout << "myvector contains:";
	for_each (myvector.begin(), myvector.end(), myfunction);
	// or:
	cout << "nmyvector contains:";
	for_each (myvector.begin(), myvector.end(), myobject);
	for_each(myvector.begin(), myvector.end(), [](int n) {
		cout << n;
		if (n % 2 == 0) {
			cout << " even ";
		} else {
			cout << " odd ";
		}
	});
	cout << endl;
	return 0;
}

As you have seen from the above example, you can literally substitute the whole struct into a single lambda method.
Initialize lambda - you also can pass values into it as shown below:

int x=3,y=4;
	for_each(myvector.begin(), myvector.end(), [x,y](int n) {
		if(x*n < 100)
			cout<<"this is less than 100";
		else
		{
			n=y;
			cout<<"N = "<<n<<endl;
		}
	});

In

Leave a Reply

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