In my project I have some custom classes, with roughly the structure below.
Point, which represents a 2D int coordinate
struct Point {
int x;
int y;
}
Line, which represents a line drawn between two Points
class Line {
Point start;
Point end;
}
Polygon, which represents the polygon that is defined by number of Points.
class Polygon {
private:
std::vector<Point> _vertices;
}
I'm trying to implement a custom iterator for Polygon, the goal being a syntax something like:
Polygon aPolygon;
Point somePoint;
for( auto line_it = aPolygon.begin(); line_it != aPolygon.end(); line_it++ ){
if( line_it->includes(somePoint) ){
// Do something
}
}
When iterating over Polygon the n:th element would be
Line( _vertices[n], _vertices[n+1] ),
and the last would be
Line( _vertices[_vertices.size() - 1], _vertices[0] )
How do I implement such an iterator, or otherwise acheive similar syntax with acceptable performance?
I'm looking through similar questions, but I've yet to find one similar enough for a comprehensive answer. If possible I would prefer a STL solution that uses c++20 standard.
I realize the question was unecessarily vague, more specifically I'm asking how I can implement the *,-> and ++ operators for my iterator.
class Polygon {
public:
/* ... */
struct PolygonIterator {
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Line;
using pointer = value_type*;
using reference = value_type&;
explicit PolygonIterator( Point* ptr ) : m_ptr( ptr ) {}
reference operator*();
// ^ Should return Line reference, but I have Point in container?
PolygonIterator& operator++();
pointer operator->();
bool operator==(const PolygonIterator& other);
private:
Point* m_ptr;
};
PolygonIterator begin() { return PolygonIterator( &_vertices.front() ); }
PolygonIterator end() { return PolygonIterator( &_vertices.back() ); }