-1

我正在尝试对坐标向量进行排序。该向量具有指向这些坐标的指针。我想按 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);
4

1 回答 1

2

It's fairly easy using a custom comparator to do the dereferencing, as well as ready-made lexicographic tuple comparison:

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

Of course the objects pointed to by the pointers must live at least as long as you're using the pointers in v, x and y.

于 2013-10-21T00:10:04.873 回答