Tuesday, July 28, 2009

Lambda Expressions

Often when using STL algorithms, you have to define a function pointer or a function object as a predicate to check a condition.
Lambda expressions or lambda functions also known as Closures in other popular languages like ruby, python etc allows you to define an anonymous (nameless) function, that allows you to maintain state.

Here's an example first using Lambda Expression and second using a Function Object.

Using Lambda Expression

Code

// even_lambda.cpp
// compile with: /EHsc
#include
#include
#include
using namespace std;

int main()
{
// Create a vector object that contains 10 elements.
vector v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}

// Count the number of even numbers in the vector by
// using the for_each function and a lambda expression.
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount] (int n) {
cout << n;

if (n % 2 == 0)
{
cout << " is even " << endl;

// Increment the counter.
evenCount++;
}
else
{
cout << " is odd " << endl;
}
});

// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}

Output

0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

Using a Function Object
// even_functor.cpp
// compile with: /EHsc
#include
#include
#include
using namespace std;

class Functor
{
public:
// The constructor.
explicit Functor(int& evenCount)
: _evenCount(evenCount)
{
}

// The function-call operator prints whether the number is
// even or odd. If the number is even, this method updates
// the counter.
void operator()(int n)
{
cout << n;

if (n % 2 == 0)
{
cout << " is even " << endl;

// Increment the counter.
_evenCount++;
}
else
{
cout << " is odd " << endl;
}
}

private:
int& _evenCount; // the number of even variables in the vector
};


int main()
{
// Create a vector object that contains 10 elements.
vector v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}

// Count the number of even numbers in the vector by
// using the for_each function and a function object.
int evenCount = 0;
for_each(v.begin(), v.end(), Functor(evenCount));

// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}