Demonstrated by std::sort

Comparing to function pointers, lambda can access all variables in enclosing scope.

Comparing to function pointers, functor have state, with help from data members in the functor class.

bool MyCompare(const int& a, const int& b)
{
return a > b;
}
class MyComparer
{
public:
MyComparer(bool bCompareByAbsValue)
{
mbCompareByAbsValue = bCompareByAbsValue;
}
bool operator()(const int& a, const int& b)
{
if (mbCompareByAbsValue)
return abs(a) > abs(b);
else
return a > b;
}
private:
bool mbCompareByAbsValue;
};
void output(string by, int * aInt, size_t nLen)
{
cout << "sort by " << by << " descending order: " << endl;
for (int i = 0; i < nLen; i++)
cout << aInt[i] << " ";
cout << endl;
}
void TestFunctionPtrFunctorLambda()
{
const int LENGTH = 3;
int nLen = LENGTH;
int aInt[LENGTH] = {2, -3, 1};
int * pInt = aInt;
std::sort(pInt, pInt + nLen, MyCompare);
output("function pointer", aInt, nLen);
bool bCompareByAbsValue = true;
std::sort(pInt, pInt + nLen,
[bCompareByAbsValue](int a, int b) {
if (bCompareByAbsValue)
return abs(a) > abs(b);
else
return a > b;
});
output("lambda, absolute value", aInt, nLen);
std::sort(pInt, pInt + nLen, MyComparer(bCompareByAbsValue));
output("functor, absolute value", aInt, nLen);
}

output:

sort by function pointer descending order:

2 1 -3

sort by lambda, absolute value descending order:

-3 2 1

sort by functor, absolute value descending order:

-3 2 1