Forms with mutable Area
polygon.cpp
Go to the documentation of this file.
1 #include "form.h"
2 #include "polygon.h"
3 
4 #include <cmath>
5 #include <iostream>
6 #include <vector>
7 using namespace std;
8 
9 
10 //---------------------------------------------------------------------------------
12  : _v(n)
13 {
14  for (unsigned int k=0; k<_v.size(); ++k)
15  {
16  _v.at(k) = Point2D( cos(k*2*M_PI/n), sin(k*2*M_PI/n) );
17  }
18 
19 // copy(_v.begin(),_v.end(), ostream_iterator<Point2D>(cout," "));
20 }
21 
23 {
24  float sum=dist( _v.front(),_v.back() ); // geschlossener Polygonzug
25  for (unsigned int k=1; k<_v.size(); ++k)
26  {
27  sum += dist( _v[k], _v[k-1] );
28  }
29  return sum;
30 }
31 
32 //---------------------------------------------------------------------------------
34  : Form(0.0F, 0.0F), _v(n), _peri(-1.0F), _area(-1.0F)
35 {
36  for (unsigned int k=0; k<_v.size(); ++k)
37  {
38  _v.at(k) = Point2D( cos(k*2*M_PI/n), sin(k*2*M_PI/n) );
39  }
40 
41 // copy(_v.begin(),_v.end(), ostream_iterator<Point2D>(cout," "));
42 }
43 
44 float Polygon::perimeter() const
45 {
46  if ( _peri<0.0F )
47  {
48  _peri=dist( _v.front(),_v.back() ); // geschlossener Polygonzug
49  for (unsigned int k=1; k<_v.size(); ++k)
50  {
51  _peri += dist( _v[k], _v[k-1] );
52  }
53  }
54 
55  return _peri;
56 }
57 
58 float Polygon::area() const
59 {
60  if ( _area<0.0F )
61  {
62  _area= crossZ(_v.back(),_v.front()); // geschlossener Polygonzug
63  for (unsigned int k=1; k<_v.size(); ++k)
64  {
65  _area += crossZ( _v[k-1], _v[k] );
66  }
67  _area = _area/2;
68  }
69 
70  return _area;
71 }
72 
Definition: form.h:73
Class containing a point in 2D.
Definition: form.h:12
float perimeter() const
Definition: polygon.cpp:22
Polygon_old(int n)
Definition: polygon.cpp:11
Polygon(int n)
Constructs a regular polygon with vertices on the unit circle.
Definition: polygon.cpp:33
float perimeter() const
Computes the perimeter of the closed polygon.
Definition: polygon.cpp:44
float area() const override
Computes the area of the closed polygon.
Definition: polygon.cpp:58
float crossZ(const Point2D &a, const Point2D &b)
Calculates z-component of the cross product of two points in 2D.
Definition: form.h:66
float dist(const Point2D &a, const Point2D &b)
Calculates the Euclidian distance between two points in 2D.
Definition: form.h:53