For C++ sort(), how to pass a parameter to custom compare function?

孤街醉人 提交于 2021-01-28 07:55:22

问题


I want to use the standard sort function for sorting points in respect to their distance of another point (e.g. 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());

回答1:


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



回答2:


You basically have a function object already, all you have to do is add a constructor to your struct that takes in the parameter(s) you need and store them in member variables to be used by operator().



来源:https://stackoverflow.com/questions/26476926/for-c-sort-how-to-pass-a-parameter-to-custom-compare-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!