简体   繁体   中英

how to organize or sort a std::vector <cv::Point2f>

I have a vector full of cv::Point and I want to organize this vector so, that the Point with the smallest x and y value should be the first and the last one should have the highst x,y value ? any Idea how can I do that ?

Use std::sort .

std::sort(vec.begin(), vec.end(), [](const cv::Point2f &a, const cv::Point2f &b) {
    return (/* This is where you would compare a and b however you want */);
});

Really, it's quite hard to tell what you deem as the greatest (x,y) pair and the least (x,y) pair. One solution is to add the coordinates to give them a magnitude.

I'd use the distance from the origin: return ax*ax + ay*ay < bx*bx + by*by


In case you can't use C++11 functionality, here's the equivalent of the above solution:

bool point_comparator(const cv::Point2f &a, const cv::Point2f &b) {
    return (/* Your expression */);
}

std::sort(vec.begin(), vec.end(), point_comparator);

If your Point class has operator < that evaluates like your rule (or you can add one), just call std::sort . Otherwise write your compare function and call std::sort second form passing it as last param. You can make it a lambda if your compiler is C++11-compatible.

Remember that the compare function must be transitive.

Let's just arbitrarily assume that you determine the value of a point by adding the x and y (big assumption). Sorting is a fairly simply process:

bool sort (const cv::Point p1, const cv::Point p2) { return (p1.x + p1.y) < (p2.x + p2.y)); }

//int main or where ever
//assuming name of vector is myVector
std::sort(myVector.begin(), myVector.end(), sort);

Just change the sort method to illustrate how you want to sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM