如何编写带有stl排序中间变量的比较器

时间:2011-12-01 11:29:42

标签: c++ sorting stl

class Point    
{    
    int x;  
}    
static Point referencePoint;
struct Comparator
{
    bool AbsComparator(const Point& p1, const Point& p2)
    {    
        return abs(p1.x - referencePoint.x) < abs(p2.x - referencePoint.x);
    }   
};    
list<Point> points;
points.sort(Comparator::AbsComparator);

但我不能使用静态referencePoint进行多线程安全,还有其他方法吗? 感谢。

4 个答案:

答案 0 :(得分:3)

让它成为Comparator

的一部分
struct Comparator
{
    Point referencePoint;

    Comparator(Point referencePoint): referencePoint(referencePoint) {}

    Comparator(const Comparator& rhs) {
        referencePoint = rhs.referencePoint;
    }

    bool operator()(const Point& p1, const Point& p2) const
    {    
        return abs(p1.x - referencePoint.x) < abs(p2.x - referencePoint.x);
    }   
};    

...

points.sort(Comparator(refP));

答案 1 :(得分:1)

为什么不简单地将referencePoint或更确切地说整数值保存在Point内作为Comparator内的成员,这样您总是可以在比较器函数中访问它。

答案 2 :(得分:1)

避免全局变量。这是编写多线程代码的开始。

改为使用局部变量:

Point referencePoint(10,20); //use local variable!

points.sort(Comparator(referencePoint));

或者简单地说,

points.sort(Comparator(Point(10,20)));

其中Comparatorfunctor,定义为:

struct Comparator
{
    Point referencePoint;

    explicit Comparator(const Point & pt) : referencePoint(pt) {}

    bool operator() (const Point& p1, const Point& p2) const
    {    
        return abs(p1.x - referencePoint.x) < abs(p2.x - referencePoint.x);
    }   
};    

你已经完成了!

请注意operator()的实施。这使得该课成为一个算符。

答案 3 :(得分:0)

您可以简单地以变构或结构化的方式存储此变量。

// destructured (only store what you need)
class ReferenceComparator {
public:
  explicit ReferenceComparator(int x): _x(x) {}
  explicit ReferenceComparator(Point const& p): _x(p.x) {}

  bool operator()(Point const& left, Point const& right) const {
    return abs(left.x - _x) < abs(right.x - _x);
  }

private:
  int _x;
}; // class ReferenceComparator

然后将其用作:

list.sort(ReferenceComparator(myReferencePoint));

如果您需要排序,我建议您不要使用listlist并不擅长......