[英]For C++ sort(), how to pass a parameter to custom compare function?
I want to use the standard sort function for sorting points in respect to their distance of another point (eg their barycenter). 我想使用标准的排序功能对点相对于另一个点的距离(例如,它们的重心)进行排序。
I know I can write a custom compare function, but I don't know how to pass a parameter to it. 我知道我可以编写一个自定义的比较函数,但是我不知道如何将参数传递给它。 I want to have it thread-safe, so I do not want to store the parameter at one central location.
我希望它具有线程安全性,因此我不想将参数存储在一个中央位置。 Is there a way how to pass additional parameters to a custom compare function?
有没有办法将其他参数传递给自定义比较函数?
// 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());
Remembering that a struct and a class are pretty much identical, add a member to the class. 记住结构和类几乎相同,请向该类添加一个成员。
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));
您基本上已经有了一个功能对象,您所要做的就是向您的结构中添加一个构造函数,该构造函数接受您需要的参数并将它们存储在供operator()使用的成员变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.