how to organize or sort a std::vector

前端 未结 3 1900
难免孤独
难免孤独 2021-01-06 14:56

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 15:43

    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 a.x*a.x + a.y*a.y < b.x*b.x + b.y*b.y


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

提交回复
热议问题