A first consideration is about comparing the usage of a functor and a lambda expression when is required to perform some operation on a sequence. In our case we would like to check how many elements in a vector of int are even. Here is a comparison between the two solutions:

#include <algorithm>

#include <iostream>

#include <vector>

using std::vector;

using std::cout;

using std::endl;

using std::for_each;

namespace

{

class EvenCount

{

int count_;

public:

explicit EvenCount() : count_(0) {}

void operator()(int n)

{

cout << n;

if(n % 2 == 0)

{

cout << " is even " << endl;

++count_;

}

else

cout << " is odd " << endl;

}

const int getCount() const { return count_; }

};

}

// Count the number of even numbers in a vector

void l03()

{

vector<int> vec;

for (int i = 0; i < 10; ++i)

vec.push_back(i);

// count using a functor

cout << "The even numbers in the vector are " <<

for_each(vec.begin(), vec.end(), EvenCount()).getCount() << endl;

// count using a lambda expression

int even = 0;

for_each(vec.begin(), vec.end(), [&even] (int n) {

cout << n;

if (n % 2 == 0)

{

cout << " is even " << endl;

even++;

}

else

cout << " is odd " << endl;

});

cout << "There are " << even << " even numbers in the vector" << endl;

}

In this case, chosing one solution or the other is basically a matter of taste. Most probably I would have taken the functor way here, since it looks to me a bit clearer.

But let's say I just had to count the even element, and not printing their single status to console. This would be the code resulting for the lambda expression:

// just counting with lambda

even = 0;

for_each(vec.begin(), vec.end(), [&even] (int n) { if(n%2 == 0) ++even; });

cout << "There are " << even << " even numbers in the vector" << endl;

I reckon it would not make much sense creating a functor, when we could write such a compact and clear piece of code instead.

## No comments:

## Post a Comment