坐标的排序向量C++
Sorting Vector of Coordinates C++
我正在尝试对坐标向量进行排序。矢量具有指向这些坐标的指针。我想按 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); });
当然,指针指向的对象必须至少与你在v
、x
和y
中使用指针一样长。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么