【问题标题】:For C++ sort(), how to pass a parameter to custom compare function?对于 C++ sort(),如何将参数传递给自定义比较函数?
【发布时间】: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());

【问题讨论】:

  • 我用谷歌搜索了质心,但它似乎涉及质量,而点没有质量。您是否尝试按距固定位置的距离对点进行排序?

标签: c++ sorting compare


【解决方案1】:

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

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

【讨论】:

  • 哇,这很容易。正是我想要的。不过我自己也想不通。谢谢!
  • 我认为构造函数名称中有错字“Point2fBarycenterComparitor”应该是“Point2fBarycenterComparator”。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2013-12-01
    • 2020-07-10
    相关资源
    最近更新 更多