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

标签 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());

最佳答案

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

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/

相关文章:

c - 对 int 数组进行排序,在 c 中被 SIGABOT 杀死

php - 从 MySQL 中的多个表中排序产品价格

c++ - 为什么我的字符串失去了它的值(value)?

java - 如何在字符串中搜索关键字

java - 如何比较2个Maps Java的值

c++ - 为什么 hash<const char*> 适用于字符串而不适用于字符串变量?

c++ - OpenCV:在哪里可以找到 CV_WINDOW_AUTOSIZE 常量?

c++ - 如何在 Eclipse 中查看 std::map 的内容?

c++ - pthread_mutex_trylock? Windows 中的线程

ios - 如何按字母顺序对二维数组中的数据进行排序?