Skip to content

Commit 87dd5d3

Browse files
committed
Add operators to make points sortable
The order is more or less arbitrary. This is only so that there is some kind of order for comparing sets of points etc.
1 parent 40f1067 commit 87dd5d3

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/geom.hpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@ class point_t
8484
return !(a == b);
8585
}
8686

87+
/// Give points an (arbitrary) order.
88+
[[nodiscard]] constexpr friend bool operator<(point_t a, point_t b) noexcept
89+
{
90+
if (a.x() == b.x()) {
91+
return a.y() < b.y();
92+
}
93+
return a.x() < b.x();
94+
}
95+
96+
[[nodiscard]] constexpr friend bool operator>(point_t a, point_t b) noexcept
97+
{
98+
if (a.x() == b.x()) {
99+
return a.y() > b.y();
100+
}
101+
return a.x() > b.x();
102+
}
103+
87104
private:
88105
double m_x = 0.0;
89106
double m_y = 0.0;

tests/test-geom-points.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,24 @@ TEST_CASE("create_point from OSM data", "[NoDB]")
6161
REQUIRE(geom.get<geom::point_t>() == geom::point_t{1.1, 2.2});
6262
}
6363

64+
TEST_CASE("point order", "[NoDB]")
65+
{
66+
geom::point_t const p{10, 10};
67+
REQUIRE_FALSE(p < p);
68+
REQUIRE_FALSE(p > p);
69+
70+
std::vector<geom::point_t> points = {
71+
{10, 10}, {20, 10}, {13, 14}, {13, 10}
72+
};
73+
74+
std::sort(points.begin(), points.end());
75+
76+
REQUIRE(points[0] == geom::point_t(10, 10));
77+
REQUIRE(points[1] == geom::point_t(13, 10));
78+
REQUIRE(points[2] == geom::point_t(13, 14));
79+
REQUIRE(points[3] == geom::point_t(20, 10));
80+
}
81+
6482
TEST_CASE("geom::distance", "[NoDB]")
6583
{
6684
geom::point_t const p1{10, 10};

0 commit comments

Comments
 (0)