Advertisement
danielperezunlpam

Polygon

May 10th, 2021
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #ifndef POLYGON_H
  2. #define POLYGON_H
  3.  
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. class Point {
  8. public:
  9.  
  10.     Point(int x = 0, int y = 0) {
  11.         this->x = x;
  12.         this->y = y;
  13.     }
  14.  
  15.     void setX(int x) {
  16.         this->x = x;
  17.     }
  18.  
  19.     void setY(int y) {
  20.         this->y = y;
  21.     }
  22.  
  23.     int getX() {
  24.         return this->x;
  25.     }
  26.  
  27.     int getY() {
  28.         return this->y;
  29.     }
  30.  
  31.     friend std::ostream &operator<<(std::ostream &o, const Point &p) {
  32.         return o << "(" << p.x << "," << p.y << ")";
  33.     }
  34.  
  35.     bool operator==(const Point &rhs) const {
  36.         return x == rhs.x &&
  37.                y == rhs.y;
  38.     }
  39.  
  40.     bool operator!=(const Point &rhs) const {
  41.         return !(rhs == *this);
  42.     }
  43.  
  44. private:
  45.     int x;
  46.     int y;
  47.  
  48. };
  49.  
  50. class Polygon {
  51. public:
  52.     Polygon() {
  53.  
  54.     };
  55.  
  56.     void push(Point p) {
  57.         points.push_back(p);
  58.     }
  59.  
  60.     void remove(const Point &p) {
  61.         std::vector<Point>::iterator it = std::find(points.begin(), points.end(), p);
  62.         if (it != points.end())
  63.             points.erase(it);
  64.     }
  65.  
  66.     unsigned int numberSegments() {
  67.         return points.size();
  68.     }
  69.  
  70.     bool isValid() {
  71.         return this->points.size() > 2;
  72.     }
  73.  
  74.     friend std::ostream &operator<<(std::ostream &o, const Polygon &p) {
  75.         o << "[";
  76.         for (auto i = p.points.begin(); i != p.points.end(); ++i)
  77.             o << *i << ((i + 1) != p.points.end() ? ", " : "");
  78.         return o << "]";
  79.     }
  80.  
  81. private:
  82.     std::vector<Point> points;
  83. };
  84.  
  85. void test_polygon() {
  86.     Polygon p;
  87.     p.push(Point(1, 1));
  88.     std::cout << "\nPolygon p: " << p;
  89.     std::cout << "\np.isValid(): " << p.isValid();
  90.     p.push(Point(3, 5));
  91.     p.push(Point(10, 10));
  92.     p.push(Point(9));
  93.     std::cout << "\nPolygon p: " << p;
  94.     std::cout << "\np.isValid(): " << p.isValid();
  95.     std::cout << "\np.numberSegments():" << p.numberSegments();
  96.     Point p1(3, 5);
  97.     p.remove(p1);
  98.     std::cout << "\nPolygon p: " << p;
  99.     std::cout << "\np.numberSegments():" << p.numberSegments();
  100.  
  101. }
  102.  
  103. #endif // POLYGON_H
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement