Archil Zhvania
Archil Zhvania

Reputation: 123

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

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?

Upvotes: 2

Views: 123

Answers (1)

Caleth
Caleth

Reputation: 62719

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

Upvotes: 2

Related Questions