You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于原点距离排序点对向量的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:25:05