基于 x 和 y 坐标进行排序
sorting based on x and y co-ordinate
我想根据x
和y
坐标对vector
进行排序。以下是我所做的,但我想要的是当我根据x
排序时,我得到了正确的,但是当我根据y
进行排序时,我不希望我的x
顺序应该改变。
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
struct item_t {
int x;
int y;
item_t( int h, int w ) : x(h), y(w) {}
friend std::ostream& operator<<(std::ostream& os, const item_t& gt) {
os << "(" << gt.x << "," << gt.y << ")";
return os;
}
};
typedef std::vector<item_t> item_list_t;
typedef item_list_t::iterator item_list_itr_t;
struct compare_x {
bool operator ()(const item_t& left, const item_t& rigx) const {
return left.x < rigx.x;
}
};
struct compare_y {
bool operator ()(const item_t& left, const item_t& rigx) const {
return left.y < rigx.y;
}
};
int main ( int argc, char **argv) {
item_list_t items;
items.push_back(item_t(15, 176));
items.push_back(item_t(65, 97));
items.push_back(item_t(72, 43));
items.push_back(item_t(102, 6));
items.push_back(item_t(191, 189));
items.push_back(item_t(90, 163));
items.push_back(item_t(44, 168));
items.push_back(item_t(39, 47));
items.push_back(item_t(123, 37));
std::sort( items.begin(), items.end(), compare_x());
std::copy(items.begin(),items.end(), std::ostream_iterator<item_t>(std::cout," ") );
std::cout << std::endl;
std::sort( items.begin(), items.end(), compare_y());
std::copy(items.begin(),items.end(), std::ostream_iterator<item_t>(std::cout," ") );
std::cout << std::endl;
}
我想要的是按递增顺序给出一组点数订单。 即 x
和y
都在增加。
您应该在一次传递中执行排序:
struct compare_xy {
bool operator ()(const item_t& left, const item_t& right) const {
return (left.x == right.x ? left.y < right.y : left.x < right.x);
}
};
您只需要创建一个比较器,并且只需要调用一次std::sort
:
struct compare_xy {
bool operator ()(const item_t& left, const item_t& right) const {
return (left.x < right.x) || ((left.x == right.x) && (left.y < right.y));
}
};
我不完全清楚你在问什么。 如果您的目标是按y
排序,x
确定y
相等时的顺序,然后使用比较函数进行排序的单个调用:
struct OrderYThenX
{
bool operator()( item_t const& lhs, item_t const& rhs ) const
{
return lhs.y < rhs.y
|| (!(rhs.y < lhs.y) && lhs.x < rhs.x);
}
};
这将导致items
具有与最终相同的顺序您的代码。
如果,从您的描述和您的部分描述中似乎更有可能例如,您希望y
S 相等的对象之间的顺序为按y
排序时保持不变,无论值如何对于x
,应使用 std::stable_sort
。 只是成为意识到它可能比 std::sort
.
相关文章:
- 二叉排序树无法编译
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 使用C++中的链表对与原点的距离、x 和 y 坐标进行排序
- 对坐标结构的向量进行排序
- 如何按坐标 x 或坐标 y 对 QGraphicsitem 的 QList 进行排序
- 在 c++ 中对插值的坐标进行排序和搜索
- 对坐标 c++ 的向量进行排序
- 根据点的坐标对点进行排序
- 如何按距点的距离(x1,y1)升序对一组坐标进行排序
- 对抛物线的坐标 (x,y) 进行排序 y=ax^2+bx+c x=x1,x2,x3, x4.根据 y 坐标
- 坐标的排序向量C++
- C++对指针向量进行排序,其中对象表示矩阵坐标
- 坐标的排序
- Make_heap和排序x和y坐标
- 基于 x 和 y 坐标进行排序
- 排序坐标从左上到右下
- 以蛇形图案排序点坐标
- 如何使用std::sort按x坐标对结构进行排序
- 排序屏幕坐标