0

我的问题与这个有关:c++ Sorting 2D Points 顺时针,但不知何故,该解决方案对我不起作用。我正在尝试逆时针排序 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)

4

2 回答 2

0
  • 要对从 12 点开始的点进行逆时针排序,首先必须将它们旋转-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, y)try atan2( x == .0f ? .0f : -x, y )- nottested

于 2018-10-31T00:12:52.717 回答
0

我相信有 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
于 2018-10-30T21:37:45.237 回答