how to organize or sort a std::vector

前端 未结 3 1893
难免孤独
难免孤独 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条回答
  • 2021-01-06 15:24

    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

    0 讨论(0)
  • 2021-01-06 15:26

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题