1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <vector>
#include <stdexcept>
struct point
{
explicit point( int xx = 0, int yy = 0 ) : x(xx), y(yy) {}
private: int x, y ;
friend std::ostream& operator<< ( std::ostream& stm, point pt )
{ return stm << '(' << pt.x << ',' << pt.y << ')' ; }
};
struct line
{
line() = default ;
explicit line( point a, point b ) : from(a), to(b) {}
private: point from, to ;
friend std::ostream& operator<< ( std::ostream& stm, const line& ln )
{ return stm << "line from " << ln.from << " to " << ln.to ; }
};
struct polygon // : public shape
{
polygon( std::initializer_list<point> pts ) : vertices(pts)
{ if( vertices.size() < 3 ) throw std::invalid_argument( "too few vertices" ) ; }
// return the edges (sides) of the polygon
// vector: https://cal-linux.com/tutorials/vectors.html
std::vector<line> edges() const
{
std::vector<line> sides ;
for( std::size_t i = 0 ; i < vertices.size() ; ++i )
sides.push_back( line( vertices[i], vertices[ (i+1) % vertices.size() ] ) ) ;
return sides ;
}
private: std::vector<point> vertices ;
friend std::ostream& operator<< ( std::ostream& stm, const polygon& poly )
{
stm << "polygon with vertices: " ;
for( point pt : poly.vertices ) stm << pt << ' ' ;
return stm ;
}
};
int main()
{
// construct line with two points a and b:
// a. point() : a default constructed point - point(0,0)
// and b. a second point(100,100)
const line some_line( point(), point(100,100) ) ;
std::cout << some_line << '\n' ; // line from (0,0) to (100,100)
const polygon a_rectangle( { point(), point(100,100), point(200,50), point(100,25) } ) ;
std::cout << "-----\n" << a_rectangle << '\n' ; // polygon with vertices: (0,0) (100,100) (200,50) (100,25)
const auto sides = a_rectangle.edges() ;
std::cout << "the " << sides.size() << " sides are:\n" ;
for( const line& ln : sides ) std::cout << " " << ln << '\n' ;
}
|