So the question statement is:
Given an int
n
, follows byn
pairs of numbers which are the coordinates of points. You must print out the point in the ordered entered, then print them in the order sorted by the distance from the origin.You will need to a
<
operator to the Point class for this to workWrite your solution in C++
Example input
5 8 9 6 5 3 4 3 5 2 6
Example output 2
(8,9) (6,5) (3,4) (3,5) (2,6) (3,4) (3,5) (2,6) (6,5) (8,9)
So, I tried to design separate functions of a class Point
that stores the pairs. Here's the cpp for my Point
class:
//Compare
bool Point::operator==(const Point& point) const {
return ((x == point.x) && (y == point.y));
}
//Distance
// d=√((x2 – x1)² + (y2 – y1)²)
double Point::operator-(const Point& point) const {
return (sqrt(pow(point.x-x,2) + pow(point.y-y,2)));
}
// Less then (add this)
bool Point::operator<(const Point& point) const {
return (((point.x) < (x))&& (point.y)<(y));
}
//Constructor acts as a mutator
//to get values
Point::Point(double new_x, double new_y)
{
x = new_x;
y = new_y;
}
//MUTATOR FUNCTIONS
void Point::SetX(double new_x)
{
x = new_x;
}
void Point::SetY(double new_y)
{
y = new_y;
}
I don't know how to write a display function for main()
that will sort the pairs and return them according to distance. How do I make the sort work?
void displayPoints(vector<Point> &points) {
// Finish
for (int i=0; i<points.size(); i++) {
cout << points[i] << " ";
}
cout << endl;
}
And in the main, I need to call sort(points.begin(),points.end()) and then displayPoints(points) and it should come out sorted