【问题标题】:How to Sort Vector of Points Based on a Y-Axis?如何根据 Y 轴对点的向量进行排序?
【发布时间】:2013-05-28 16:09:52
【问题描述】:

我有一组坐标例如:

10,40; 9,27; 5,68; 7,55; 8,15;

如何在不丢失已排序 Y 轴的正确 X 轴的情况下对这些坐标进行排序。

从上面的示例中,我想对坐标进行排序,以便正确的输出为:

8,15; 9,27; 10,40; 7,55; 5,68。

任何建议将不胜感激。 谢谢。

【问题讨论】:

    标签: c++ algorithm opencv


    【解决方案1】:

    Documentation for std::sort

    #include "opencv2/core/core.hpp"
    #include <algorithm>    // std::sort
    
    // This defines a binary predicate that, 
    // taking two values of the same type of those 
    // contained in the list, returns true if the first 
    // argument goes before the second argument
    struct myclass {
        bool operator() (cv::Point pt1, cv::Point pt2) { return (pt1.y < pt2.y);}
    } myobject;
    
    int main () {
        // input data
        std::vector<cv::Point> pts(5);
        pts[0] = Point(10,40);
        pts[1] = Point(9,27);
        pts[2] = Point(5,68);
        pts[3] = Point(7,55);
        pts[4] = Point(8,15);
    
        // sort vector using myobject as comparator
        std::sort(pts.begin(), pts.end(), myobject);
    }
    

    【讨论】:

    • 嗨@Alex,它非常有用,但在我的情况下,在 algorithm.cpp 类中出现错误“没有匹配函数调用 myclass 类型的对象”。
    【解决方案2】:

    您需要指定存储坐标组的精确程度。

    最简单的方法是将它们存储为您创建的新结构并在其顶部应用基本冒泡排序算法,使用 Y 值作为排序参数。然后,当您“交换”结构的位置时,X 和 Y 保持在一起。

    struct Vector {
      float x;
      float y;
    };
    

    【讨论】:

    • 谢谢你的回答,其实我用std::vector&lt;cv::Point&gt;存储积分。除了将其再次存储在struct 中之外,您还有其他建议吗?
    【解决方案3】:

    您可以创建一个映射坐标的类,如果您使用 STL 作为向量,则可以使用 sort method 根据 Y 坐标对整个向量进行排序。

    Herehere 是来自堆栈的类似问题。

    【讨论】:

    • 感谢您的建议,从您发布的参考资料中可以帮助我解决问题。我先试试看。
    猜你喜欢
    • 2022-08-18
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2011-01-23
    • 2017-07-08
    • 2015-09-03
    相关资源
    最近更新 更多