Skip to content

Instantly share code, notes, and snippets.

@adennie
Last active March 19, 2021 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adennie/01a407581960dabd1f7d8e8e5b9c2fb1 to your computer and use it in GitHub Desktop.
Save adennie/01a407581960dabd1f7d8e8e5b9c2fb1 to your computer and use it in GitHub Desktop.
#include "BoundingBox.h"
BoundingBox::BoundingBox(vector<Point> points) :
top_left(points[(0)]), bottom_right(points[1]) {
if (top_left.x > bottom_right.x || top_left.y > bottom_right.y) {
string msg("Invalid points for BoundingBox. Bottom right must have (x,y) >= top right point.");
cerr << msg.c_str() << endl;
throw runtime_error(msg);
}
}
bool BoundingBox::operator==(const BoundingBox& other) const {
return top_left == other.top_left && bottom_right == other.bottom_right;
}
int BoundingBox::area() {
return (bottom_right.x - top_left.x) * (bottom_right.y - top_left.y);
}
bool BoundingBox::contains(BoundingBox other) {
return top_left.x <= other.top_left.x && top_left.y <= other.top_left.y
&& bottom_right.x >= other.bottom_right.x && bottom_right.y >= other.bottom_right.y;
}
#pragma once
#include <vector>
#include <iostream>
using namespace std;
// An [x/y] coordinate, relative to an upper left origin (positive Y is down, positive X to the right)
class Point {
public:
// Instantiate a Point with default values
Point() : x(0), y(0) {}
// Instantiate a Point with provided values
Point(int x, int y) : x(x), y(y) {}
// Compares two Points for equality
bool operator==(const Point & other) const {
return x == other.x && y == other.y;
}
// X coordinate
int x;
// Y coordinate
int y;
};
// A rectangular region defined by two points - a top left corner and a bottom right corner.
class BoundingBox {
public:
// Initializes a BoundingBox from a vector of Points.
// The element at index 0 is used as the top left corner, and the
// element at index 1 is used as the bottom right corner.
// Throws if the bottom right corner's (x,y) coordinates are
// not >= than the upper left's ones
BoundingBox(vector<Point> corners);
// Compares two BoundingBoxes for equality
bool operator==(const BoundingBox& other) const;
// Returns the top left Point of the bounding box
Point getTopLeft() { return top_left; }
// Returns the bottom right Point of the bounding box
Point getBottomRight() { return bottom_right; }
/// Calculates the area of the bounding box
int area();
/// Determines if one BoundingBox contains another
/// <returns>true if this BoundingBox contains other</returns>
bool contains(BoundingBox other);
private:
Point top_left;
Point bottom_right;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment