我的问题与以下问题有关: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)
答案 0 :(得分: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
答案 1 :(得分:0)
要对从12点开始逆时针排序的点进行排序,首先必须将它们{-{3}} -90度(12点变成3点):
x’ = y
y’ = -x
rotate使用参数符号计算象限。以下几行不相等:
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)
,请尝试atan2( x == .0f ? .0f : -x, y )
-未经测试。