Daniel S.
Daniel S.

Reputation: 6640

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

Upvotes: 3

Views: 3283

Answers (2)

Mooing Duck
Mooing Duck

Reputation: 66922

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

Upvotes: 4

peterjb
peterjb

Reputation: 819

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().

Upvotes: 2

Related Questions