基于Y轴如何对点向量进行排序?

10
我有一组坐标,例如:
10,40; 9,27; 5,68; 7,55; 8,15;
请问如何对这些坐标进行排序,同时不改变它们的正确X轴位置。
以上例为例,我想要将这些坐标排序,使正确的输出结果为:
8,15; 9,27; 10,40; 7,55; 5,68.
任何建议都将不胜感激。 谢谢。
3个回答

22

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没有匹配的函数调用”。 - Madhubalan K

1
你需要指定如何存储坐标组。最简单的方法是将它们存储为新的结构体,然后应用基本的冒泡排序算法,使用Y值作为排序参数。当你“交换”结构体的位置时,X和Y会一起移动。请保留html标签。
struct Vector {
  float x;
  float y;
};

谢谢你的回答,实际上我是用 std::vector<cv::Point> 存储这些点。除了再次将它们存储在一个 struct 中,你还有其他建议吗? - anarchy99

0
你可以创建一个映射坐标的类,如果你使用STL作为你的向量,你可以使用sort方法基于Y坐标对整个向量进行排序。 这里这里是来自Stack的类似问题。

谢谢您的建议,从您发布的参考资料中可能会帮助我解决问题。我会先尝试一下。 - anarchy99

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接