I tried a modified input file:
Line2D, [5, 7], [3, 8]
Line2D, [-14, 40], [50, 3] |
Which was apparently being read correctly from the file, but only the first line was being stored in the
set<Line2D> linetwod
.
Why would that be? Well, a set checks that its elements are unique, and makes use of the comparison function
1 2 3 4 5 6 7 8
|
bool Line2D::operator < (const Line2D& rhs) const
{
if (x < rhs.x)
return true;
if ((x == rhs.x) && (y < rhs.y))
return true;
return false;
}
|
That seems to compile, but it doesn't do anything very useful. What are x and y anyway? A line starts at pt1 and ends at pt2, each of which are points having their own x,y coordinates. Where does the extra x and y fit in to all of this?
The problem is here in Line2D.h
|
class Line2D : public Point2D
|
that is, a line is inheriting from Point2D, hence it gets an extra x and y.
Change that to simply
As a result, the compare function will need changing to something more suitable,
where instead of testing x and y, it will test pt1 and pt2.
You can directly re-use the same code where the only problem arises in the expression
(x == rhs.x)
which now becomes
(pt1 == rhs.pt1)
. But the compiler doesn't know how to test whether two points are equal, so you need to add that in Point2.h and .cpp
1 2 3 4
|
bool Point2D::operator == (const Point2D & rhs) const
{
return ((x == rhs.x) && (y == rhs.y));
}
|
I feel like I've given bits of code without much explanation - you do need to try to understand it, and if it doesn't make sense, feel free to ask.
The output I get is this, which seems correct:
P1-X P1-Y P2-X P2-Y Length
----------------------------------------------------
[-14, 40] [50, 3] 73.926
[5, 7] [3, 8] 2.236 |