对由两个点组成的线段进行排序

Ordering line segments consisting of two points

本文关键字:排序 段进行 两个      更新时间:2023-10-16

我将如何为由起点和终点组成的线段实现运算符<。我想将线段插入到地图中,这样顺序就不需要是语义的,但它应该适用于所有情况。

按字典顺序排列所有内容:

struct Point { int x; int y; };
bool operator<(Point const & a, Point const & b)
{
    return (a.x < b.x) || (!(b.x < a.x) && (a.y < b.y));
}

或者使用现成的比较器tuple

#include <tuple>
// ...
return std::tie(a.x, a.y) < std::tie(b.x, b.y);

或者实际上使用std::tuple<int, int>来表示您的积分,什么都不做!

然后,对行执行相同的操作:

struct LineSegment { Point x; Point y; };
// repeat same code as above, e.g.
bool operator<(LineSegment const & a, LineSegment const & b)
{
    return std::tie(a.x, a.y) < std::tie(b.x, b.y);
}

重复一遍,完全不工作的解决方案只是一直使用元组:

typedef std::tuple<int, int> Point;
typedef std::tuple<Point, Point> LineSegment;
// everything "just works"