如何排序向量的点基于一个y轴

How to Sort Vector of Points Based on a Y-Axis?

本文关键字:于一个 向量 何排序 排序      更新时间:2023-10-16

我有一组坐标,例如:

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

如何对这些坐标排序而不丢失正确的y轴的x轴。

在上面的例子中,我想对坐标进行排序,这样正确的输出将是:

8、15;9日,27日;10、40;7, 55岁;68 .

任何建议都将非常感谢。谢谢你。

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

您需要指定如何准确地存储您的坐标组。

最简单的方法是将它们存储为您创建的新结构体,并在其上应用基本的冒泡排序算法,使用Y值作为排序参数。然后当你"交换"结构体的位置时,X &你们待在一起。

struct Vector {
  float x;
  float y;
};

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

这里和这里是来自stack的类似问题