How to sort w.r.t. certain parameter using C++ custom compare function?

118 Views Asked by At

I am trying to sort points on a plane by their polar angle w.r.t. the point O. The simplified version of the code looks like this:

bool comparePolar(point A, point B, point O){
    //if point B lies to the left of the edge OA, return false
    //return true
}

So, how to pass the point O to this function when the sort function is called, which will use comparePolar as its compare function?

1

There are 1 best solutions below

0
On

You need to construct a function object that holds O (or a reference to it). The easiest way is with a lambda

// initialised wherever
std::vector<point> points;
point O;

// Capture O by value
auto cmp = [O](point A, point B) { return comparePolar(A, B, O); };
std::sort(points.begin(), points.end(), cmp);