我想使用标准排序函数根据点与另一点的距离(例如重心)对点进行排序。
我知道我可以编写自定义比较函数,但我不知道如何将参数传递给它。我想让它线程安全,所以我不想将参数存储在一个中央位置。有没有办法将附加参数传递给自定义比较函数?
// 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));
关于c++ - 对于 C++ sort(),如何将参数传递给自定义比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476926/