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,还有其他方法吗?
谢谢。

最佳答案

使其成为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));

09-08 08:40