Kapa11
Kapa11

Reputation: 303

Sorting list with extra arguments to comparison function

Given the following

class Coordinate {
  int i,j;
};

list<shared_ptr<Coordinate>> coordinates;

(Coordinate is just a much simpler version of what my code really contains.) I want to sort the list with respect to minimal Euclidean distance to a given coordinate iCenter,jCenter. The Coordinate which is closest to this coordinate should be at first position in the list coordinates. Furterhmore, I want to use following structure

struct ComparatorForCoordinate {
  bool operator() (const shared_ptr<Coordinate>& c1, const shared_ptr<Coordinate>& c2) {
    // return distance(c1 to center) > distance(c2 to center)
  }
};

// sorting:
coordinates.sort(ComparatorForCoordinate());

My problem is that my operator() needs to know the coordinate iCenter,jCenter. How can I pass these two double values to the comparison-function? The naive try just to let the operator additionally have two double parameters for the center position did not work. This call would be great for me if it would work:

coordinates.sort(ComparatorForCoordinate(iCenter,jCenter));

Upvotes: 1

Views: 89

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

You can add state to your comparator:

struct ComparatorForCoordinate {
  ComparatorForCoordinate(Coordinate center) : _center(center) {}

  bool operator() (const shared_ptr<Coordinate>& c1, const shared_ptr<Coordinate>& c2) const {
    return distance(c1, _center) > distance(c2, _center);
  }

private:
  Coordinate _center;
};

// sorting:
coordinates.sort(ComparatorForCoordinate(center));

Upvotes: 3

Related Questions