所以问题陈述是:
给定一个 int
,后面跟着n
对数字,它们是点的坐标。您必须按输入的顺序打印出点,然后按照与原点的距离排序的顺序打印它们。n
你需要一个
操作员到 Point 类才能工作<
用 C++ 编写解决方案
示例输入
5 8 9 6 5 3 4 3 5 2 6
示例输出 2
(8,9) (6,5) (3,4) (3,5) (2,6) (3,4) (3,5) (2,6) (6,5) (8,9)
所以,我尝试设计一个类的单独函数
Point
来存储对。这是我的 Point
课程的 cpp:
//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;
}
我不知道如何为
main()
编写一个显示函数,它将对对进行排序并根据距离返回它们。我如何进行排序?
void displayPoints(vector<Point> &points) {
// Finish
for (int i=0; i<points.size(); i++) {
cout << points[i] << " ";
}
cout << endl;
}
主要是,我需要调用 sort(points.begin(),points.end()) ,然后调用 displayPoints(points) ,结果应该是 sorted
你已经有了计算两点之间距离的算法。您只需要将该算法应用于您的
operator<
(即,它不属于operator-
)。如果operator<
(被比较的左手true
)比输入点(被比较的右手this
)更接近原点,您的Point
应该返回Point
,否则返回false
.
例如,尝试这样的事情(假设原点是
(0,0)
):
//Distance
// d=√((x2 – x1)² + (y2 – y1)²)
bool Point::operator<(const Point& point) const {
const Point origin{0, 0};
double distance1 = sqrt(pow(x - origin.x, 2) + pow(y - origin.y, 2));
double distance2 = sqrt(pow(point.x - origin.x, 2) + pow(point.y - origin.y, 2));
return distance1 < distance2;
}
然后您可以使用
std::sort()
实现排序,例如:
#include <iostream>
#include <vector>
#include <algorithm>
void display(const std::vector<Point>& points) {
for(const auto &point: points) {
std::cout << '(' << point.x << ',' << point.y << ") ";
}
std::cout << std::endl;
}
...
std::vector<Point> points;
int count;
std::cin >> count;
for(int i = 0; i < count; ++i)
{
double x, y;
std::cin >> x >> y;
points.emplace_back(x, y);
}
display(points);
std::sort(points.begin(), points.end());
display(points);