C++ 不服从排序函数的向量排序
我试着按照顺时针的顺序对点向量进行排序,大约是0,0,基于 sort函数的逻辑是有意义的,当我手动计算单个点的结果时,它会检查出来。但是,结果向量似乎没有按照排序函数进行排序。例如,以下是一次特定的排序运行后的前4个元素:C++ 不服从排序函数的向量排序,c++,xcode,c++11,geometry,C++,Xcode,C++11,Geometry,我试着按照顺时针的顺序对点向量进行排序,大约是0,0,基于 sort函数的逻辑是有意义的,当我手动计算单个点的结果时,它会检查出来。但是,结果向量似乎没有按照排序函数进行排序。例如,以下是一次特定的排序运行后的前4个元素: [22.3701,450.519,-1045] <- correct [-22.429,-29.0513,-1006] <- should be in position 2 [-147.806,65.0482,-1095] <- should be
[22.3701,450.519,-1045] <- correct
[-22.429,-29.0513,-1006] <- should be in position 2
[-147.806,65.0482,-1095] <- should be in position 3
[68.0652,590.091,-942] <- should be in position 1
[22.3701450.519,-1045]正如我所怀疑的那样(实际上比我所怀疑的更糟)。我试过这个密码
int main()
{
Vec3f a(22.3701, 450.519, -1045);
Vec3f b(-22.429,-29.0513,-1006);
if (sortVectorsClockwise(a, b))
cout << "a<b\n";
if (sortVectorsClockwise(b, a))
cout << "b<a\n";
}
intmain()
{
Vec3f a(22.3701,450.519,-1045);
VEC3FB(-22.429,-29.0513,-1006);
if(按SortVector顺时针方向(a、b))
几乎可以肯定,排序函数没有定义严格的弱排序函数,并且只有在角度没有提供差异的情况下才使用长度。我仍然想知道为什么代码无法提供预期的结果。是什么阻止了您输出每次比较的结果,您似乎已经有了一个测试用例?谢谢,是的,通过找到y轴的角度重新实现是的,刚刚实现了每个time我手动验证了它,我假设每个点都会在a
位置传递:P显然,这会导致非常慢的排序功能。
if ( 68.0652 >= 0 && -22.429 < 0 ) return true
bool sortVectorsClockwise( const Vec3f &a, const Vec3f &b )
{
if ( a.x >= 0 && b.x < 0 ) return true;
if ( a.x == 0 && b.x == 0 ) return a.y > b.y;
float det = a.x * b.y - b.x * a.y;
if ( det < 0 ) return true;
if ( det > 0 ) return false;
// points a and b are on the same line from the center, check which is
// closer to the center
return a.xy().length() > b.xy().length();
}
sort( points.begin(), points.end(), sortVectorsClockwise );
for ( auto &p : points ) {
cout << p << endl;
}
int main()
{
Vec3f a(22.3701, 450.519, -1045);
Vec3f b(-22.429,-29.0513,-1006);
if (sortVectorsClockwise(a, b))
cout << "a<b\n";
if (sortVectorsClockwise(b, a))
cout << "b<a\n";
}
a<b
b<a