排序C ++坐标向量

时间:2013-10-21 00:06:14

标签: c++ sorting vector copying

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

1 个答案:

答案 0 :(得分:2)

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

#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中的指针一样长。