Lambda vs函数进行排序 [英] Lambda vs function for sorting

查看:53
本文介绍了Lambda vs函数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课

  class Point{私人的:int x;int y;上市:点(int a,int b):x(a),y(b){}Point():Point(0,0){}} 

如果我想对 Point s的向量进行排序,我应该使用lambda:

  std :: sort(xSortedPoints.begin(),xSortedPoints.end(),[](const cv :: Point& p1In,const cv :: Point& p2In)->布尔{返回(p1In.x< p2In.x);}); 

或在类中使用静态函数:

  std :: sort(xSortedPoints.begin(),xSortedPoints.end(),xSorting); 

其中 xSorting 定义并在 Point 类中声明为

 静态布尔xSorting(const Point& p1In,const Point& p2In){返回(p1In.x< p2In.x);} 

我为什么要使用lambda,否则为什么不使用?


因为我需要用两种方式(通过 x 和通过 y 进行排序),所以我没有定义< 运算符./p>

基于评论和答案,我需要说的是,我在连续运行的应用程序中使用它,因此排序已完成很多次.那么,在我的情况下,最好使用什么:静态或lambda?每次使用 std :: sort 都会创建Lambda吗?如果可以,那么我认为静态是最好的选择……否?

解决方案

Lambda可以使代码更加简洁,特别是在您的情况下,它是一种单行代码.另一方面,我认为如果需要或可以在超过1个地方使用静态函数方法,则该方法将是更可取的.

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 Points, 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.

这篇关于Lambda vs函数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆