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

For C++ sort(), how to pass a parameter to custom compare function?

本文关键字:参数传递 自定义 比较 函数 C++sort 对于      更新时间:2023-10-16

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

我知道我可以编写一个自定义的比较函数,但我不知道如何将参数传递给它。我希望它是线程安全的,所以我不想将参数存储在一个中心位置。有没有一种方法可以将额外的参数传递给自定义比较函数?

// 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());

记住结构和类几乎相同,请向类中添加一个成员。

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));

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