Sunday 15 April 2012

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



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

i want utilize standard sort function sorting points in respect distance of point (e.g. barycenter).

i know can write custom compare function, don't know how pass parameter it. want have thread-safe, not want store parameter @ 1 central location. there way how pass additional parameters custom compare function?

// here compare function without parameter sorting x-coordinate struct point2fbyxcomparator { bool operator ()(point2f const& a, point2f const& b) { homecoming a.x > b.x; } }; // here outline of comparator, can used sort in respect // point. don't know how pass other point compare // function: struct point2finrespecttootherpointcomparator { bool operator ()(point2f const& a, point2f const& b) { float distancea = distance(a, barycenter); float distanceb = distance(b, barycenter); homecoming distancea > distanceb; } }; std::vector<point2f> vec = ...; point2f barycenter(0, 0); (int = 0; < vec.size(); i++) { barycenter += vec[i]; } barycenter *= (1.0/vec.size()); // in next line have pass barycenter compare function // can utilize barycenter comparison. don't know how // this. sort(vec.begin(), vec.end(), point2finrespecttootherpointcomparator());

remembering struct , class pretty much identical, add together fellow member 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); homecoming distancea > distanceb; } point2f barycenter; }; std::vector<point2f> vec = ...; point2f barycenter = ...; sort(vec.begin(), vec.end(), point2fbarycentercomparator(barycenter));

c++ sorting compare

No comments:

Post a Comment