【发布时间】:2014-10-21 00:07:01
【问题描述】:
我想使用标准排序功能来根据点与另一个点的距离(例如它们的重心)对点进行排序。
我知道我可以编写一个自定义比较函数,但我不知道如何将参数传递给它。我希望它是线程安全的,所以我不想将参数存储在一个中心位置。有没有办法将其他参数传递给自定义比较函数?
// 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());
【问题讨论】:
-
我用谷歌搜索了质心,但它似乎涉及质量,而点没有质量。您是否尝试按距固定位置的距离对点进行排序?