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

fun*_*ash 0 c++ graphics operators line

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

Ker*_* SB 5

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

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));
}
Run Code Online (Sandbox Code Playgroud)

或者使用现成的比较器tuple

#include <tuple>

// ...

return std::tie(a.x, a.y) < std::tie(b.x, b.y);
Run Code Online (Sandbox Code Playgroud)

或者实际上使用 astd::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);
}
Run Code Online (Sandbox Code Playgroud)

再说一遍,根本不用工作的解决方案只是一直使用元组:

typedef std::tuple<int, int> Point;
typedef std::tuple<Point, Point> LineSegment;
// everything "just works"
Run Code Online (Sandbox Code Playgroud)