对于C ++ sort(),如何将参数传递给自定义比较函数?

时间:2014-10-21 00:07:01

标签: c++ sorting compare

我想使用标准排序函数来根据它们与另一个点(例如它们的重心)的距离对点进行排序。

我知道我可以编写自定义比较函数,但我不知道如何将参数传递给它。我想让它具有线程安全性,所以我不想将参数存储在一个中心位置。有没有办法将其他参数传递给自定义比较函数?

// Here is a compare function without a parameter for sorting by the x-coordinate
struct Point2fByXComparator {
    bool operator ()(Point2f const& a, Point2f const& b) {
        return a.x > b.x;
    }
};

// Here is the outline of another comparator, which can be used to sort in respect
// to another point. But I don't know how to pass this other point to the compare
// function:
struct Point2fInRespectToOtherPointComparator {
    bool operator ()(Point2f const& a, Point2f const& b) {
        float distanceA = distance(a, barycenter);
        float distanceB = distance(b, barycenter);

        return distanceA > distanceB;
    }
};

std::vector<Point2f> vec = ...;

Point2f barycenter(0, 0);
for (int i = 0; i < vec.size(); i++) {
    barycenter += vec[i];
}
barycenter *= (1.0/vec.size());

// In the next line I would have to pass the barycenter to the compare function
// so that I can use the barycenter for comparison. But I don't know how to do
// this.
sort(vec.begin(), vec.end(), Point2fInRespectToOtherPointComparator());

2 个答案:

答案 0 :(得分:3)

记住结构和类几乎完全相同,在类中添加一个成员。

struct Point2fBarycenterComparator {
    explicit Point2fBarycenterComparitor(Point2f barycenter_) 
    : barycenter(barycenter_) {}

    bool operator ()(Point2f const& a, Point2f const& b) const {
        float distanceA = distance(a, barycenter);
        float distanceB = distance(b, barycenter);

        return distanceA > distanceB;
    }

    Point2f barycenter;
};

std::vector<Point2f> vec = ...;
Point2f barycenter = ...;
sort(vec.begin(), vec.end(), Point2fBarycenterComparator(barycenter));

答案 1 :(得分:1)

你基本上已经有了一个函数对象,你所要做的就是在你的struct中添加一个构造函数,它接受你需要的参数并将它们存储在operator()中使用的成员变量中。