坐标的排序向量C++

Sorting Vector of Coordinates C++

本文关键字:C++ 向量 排序 坐标      更新时间:2023-10-16

我正在尝试对坐标向量进行排序。矢量具有指向这些坐标的指针。我想按 x 和按 y 对它们进行排序。我目前正在考虑如何做到这一点,如下所示,制作向量的两个副本,然后对它们进行排序。我不确定以下两件事:1) 如何复制指针向量2)如何在向量中按x和y对点进行排序,并确保它们正确排序如下(1,4),(1,5)

我一直在阅读并试图弄清楚是否有任何内置函数,但我不确定例如排序函数是否会正确排序 x 和 y。

这是我到目前为止所拥有的,任何帮助将不胜感激。

typedef struct{double x; double y;) pt;
vector<pt*>v1;
vector<pt*>*v2 = v1;
// allocate memory for the points and push_back on the vector
the vector would have the following points {(1,7),(4,4),(1,3),(-2,4)}

当它被排序为 x 时,它将是X={(-2,4),(1,3),(1,7),(4,4)} 和Y={(1,3),(-2,4),(4,4),(1,7)}


更新:

我目前处于这个阶段,但它仍然不起作用... :(

bool compare(pt* m1, pt* m2){return(m1->x <= m2->x) && (m1->y <= m2->y);}
vector<pt*>v1_x = v1;
sort(v1_x.begin(), v1_x.end(), comparer);

使用自定义比较器进行取消引用以及现成的词典元组比较相当容易:

#include <algorithm>
#include <tuple>
#include <vector>
struct pt { double x, double y };
std::vector<pt*> v = /* ... */ ;
auto x = v, y = v;   // copies
std::sort(x.begin(), x.end(),
          [](pt * a, pt * b) -> bool
          { return std::tie(a->x, a->y) < std::tie(b->x, b->y); });
std::sort(y.begin(), y.end(),
          [](pt * a, pt * b) -> bool
          { return std::tie(a->y, a->x) < std::tie(b->y, b->x); });

当然,指针指向的对象必须至少与你在vxy中使用指针一样长。