基于原点距离排序点对向量的C++实现问题求助
问题修正方案
1. 修正<运算符重载逻辑
要实现按点到原点的距离排序,核心是比较两个点到原点的距离大小。为避免浮点运算的精度误差,推荐直接比较距离的平方(距离平方的大小关系与距离本身完全一致)。
正确的Point类实现(含运算符重载):
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Point { private: int x, y; public: Point(int x = 0, int y = 0) : x(x), y(y) {} // 计算到原点的距离平方 int distanceSq() const { return x*x + y*y; } // 重载<运算符,按到原点的距离平方从小到大排序 bool operator<(const Point& other) const { return this->distanceSq() < other.distanceSq(); } // 友元声明,允许ostream访问私有成员 friend ostream& operator<<(ostream& os, const Point& p); }; // 重载ostream的<<运算符,让cout可直接输出Point对象 ostream& operator<<(ostream& os, const Point& p) { os << "(" << p.x << ", " << p.y << ")"; return os; }
2. 完善display函数
如果需要批量输出点向量,可编写如下display函数,直接利用重载的<<运算符实现打印:
// 输出向量中所有点 void display(const vector<Point>& points) { for (const auto& p : points) { cout << p << " "; } cout << endl; }
3. 完整调用示例
int main() { int n; cout << "输入点的数量: "; cin >> n; vector<Point> points; for (int i = 0; i < n; ++i) { int x, y; cin >> x >> y; points.emplace_back(x, y); } // 按输入顺序输出 cout << "输入顺序的点: "; display(points); // 调用sort排序(依赖重载的<运算符) sort(points.begin(), points.end()); // 排序后输出 cout << "按到原点距离排序后的点: "; display(points); return 0; }
关键修正说明
- 原
<运算符大概率错误比较了x/y坐标而非距离,现在改为比较距离平方,确保排序逻辑符合需求。 - 重载
ostream& operator<<是让display函数(或直接cout)能输出Point对象的核心,无需额外复杂逻辑即可打印坐标。 - 使用距离平方而非实际距离,避免了
sqrt带来的浮点精度损失,同时计算效率更高。
内容的提问来源于stack exchange,提问作者sturggler
相关产品推荐
相关产品推荐

