【问题标题】:Sort 2D points counter clockwise逆时针排序二维点
【发布时间】:2018-10-30 21:11:43
【问题描述】:

我的问题与这个问题有关:c++ Sorting 2D Points clockwise,但不知何故,该解决方案对我不起作用。我正在尝试逆时针排序 4 个 2d 点。

这是我的代码:

typedef struct p {
float x,y;
} Point;

double getClockwiseAngle(Point p) {
double angle = 0.0;

angle = atan2(p.x, -p.y);
return angle;
}

bool comparePoints(Point p1, Point p2) {
     return getClockwiseAngle(p1) < getClockwiseAngle(p2);
}

int main() {
    ...
    sort(givenPoints.begin(), givenPoints.end(), comparePoints);
    ...
}

示例: 输入 (-4, 2), (1, 4), (0,1), (-1, 4)

输出 (-4, 2), (-1, 4), (1, 4), (0,1)

【问题讨论】:

  • 答案是使用-atan2。您正在使用atan2。看出区别了吗?
  • 是的,你是对的,但输出仍然是错误的,只是现在点的顺时针排序不正确,而不是逆时针。
  • 嗯,这就是你复制的。如果您不更改任何内容,则不会以不同的方式排序。您可能需要将getClockwiseAngle(p1) &lt; getClockwiseAngle(p2) 更改为getClockwiseAngle(p1) &gt; getClockwiseAngle(p2)
  • 改变你告诉我的只是把我带到我原来的输出。您基本上是将“-”从一个地方移动到另一个地方。

标签: c++ sorting 2d points convex


【解决方案1】:

我认为有 2 个负面迹象需要修复,如评论中所示。这似乎有效:

#include <iostream>
#include <vector>
#include <cmath>

typedef struct p {
    float x,y;
} Point;

double getClockwiseAngle(Point p) {
    double angle = 0.0;

    angle = -1 * atan2(p.x, -1 * p.y);
    return angle;
}

bool comparePoints(Point p1, Point p2) {
    return getClockwiseAngle(p1) < getClockwiseAngle(p2);
}

int main() {
    std::vector<Point> givenPoints{{-4,2}, {1,4}, {0,1}, {-1,4}};
    sort(givenPoints.begin(), givenPoints.end(), comparePoints);
    std::cout << "Sorted Points: ";

    for(auto it = givenPoints.begin(); it != givenPoints.end(); it++) {
        std::cout << "(" << it->x << ", " << it->y << ")" ;
    }
    std::cout << std::endl;

}

输出:

Sorted Points: (0, 1)(1, 4)(-4, 2)(-1, 4)

Process finished with exit code 0

【讨论】:

  • 这正是我最终实现它的方式,但它仍然没有输出正确的答案。正确的是 (0, 1), (1, 4), (-1, 4), (-4, 2)。你的程序和我的程序都不会输出这个结果。
  • 绕圆顺时针移动,(-4,2) 在 (-1,4) 之前。在一张方格纸上画出来。程序运行正常。
【解决方案2】:
  • 要从 12 点开始逆时针排序,您首先必须 rotate 它们 -90 度(12 点变为 3 点):

    x’ = y
    y’ = -x
    
  • atan2 正在使用参数符号来计算象限。以下几行不等价:

    bool b = atan2(0.0, 1.0) < atan2(0.0, -1.0); // true
    bool b = atan2(-0.0, 1.0) < atan2(-0.0, -1.0); // false
    

    因此您不能使用atan2 对点进行排序。

atan2( x == .0f ? .0f : -x, y ) 代替atan2( -x, y) - 未测试

【讨论】:

  • atan() 或 atan2() 似乎太贵了。一个简单的 y/x 应该可以解决问题。但是,必须实现正、零和负 x 的不同情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 2011-10-16
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多