I have a class
class Point
{
private:
int x; int y;
public:
Point(int a, int b):x(a),y(b){}
Point():Point(0,0){}
}
If I want to sort a vector of Point
s, shall I use a lambda:
std::sort(xSortedPoints.begin(), xSortedPoints.end(),
[](const cv::Point& p1In, const cv::Point& p2In) -> bool {
return (p1In.x < p2In.x);
});
or using a static function in the class:
std::sort(xSortedPoints.begin(), xSortedPoints.end(), xSorting);
where xSorting
is defined and declared in the Point
class as
static bool xSorting(const Point& p1In, const Point& p2In)
{
return (p1In.x < p2In.x);
}
Why shall I use lambda, or why not?
EDIT:
Because I need to sort in the two ways (by x
and by y
) I did not define the <
operator.
Based on the comments and answers I need to say that I use this in an application that runs continuously, so the sorting is done a lot of times. So what is better to use in my case: static or lambdas? Lambdas are created every time the std::sort
is used? If yes, than I think static is the best choice... No?
Lambda would make the code more concise especially if it's a one-liner like in your case. On the other hand, I would think the static function approach would be prefered if it needs to or can be used in more than 1 place.
Lambdas are there for convenience and slick code.
If you prefer to use a static function you should do this. If you use it once consider a lambda.
To my knowledge there is no performance gain when using lambdas.
So either do a static function, put an in place lambda or define less than operator for the class.
This is kind of opinion based but in short:
If it is short and not used often, use a lambda. Your example is short enough. If the function is long or complicated or used often, give it a name.
In this special case, you could think about overloading operator <
for Point
if it makes sense. Then, no third argument to sort
would be required, but you have make sure that <
does what the naive reader would expect.
Btw, you can omit the ->bool
, the compiler will deduce it automatically.
I don't know if there is any performance issues here, and the answers you get are going to be of the type "IM(H)O ....", so here are my two cents:
In this case, lambda is good in the sense that it shows the person who is reading the code what you mean by comparing two points. Mathematically, 2D (or any higher dimensions for that matter) points don't form an ordered set, so a <
operator will be confusing. Having a static function, friend, ... on the other hand puts the definition of the comparison too far from the usage and, again, might add to confusion as the reader has to scroll to the definition to see what you mean by comparing two points.