所以我寫了基於尋找一組點的凸包的禮品包裝算法的例子下面的代碼:禮品包裝算法共線點
std::vector<sf::Vector2f> convexHull(const std::vector<sf::Vector2f>& _shape)
{
std::vector<sf::Vector2f> returnValue;
returnValue.push_back(leftmostPoint(_shape));
for (std::vector<sf::Vector2f>::const_iterator it = _shape.begin(), end = _shape.end(); it != end; ++it)
{
if (elementIncludedInVector(*it, returnValue)) continue;
bool allPointWereToTheLeft = true;
for (std::vector<sf::Vector2f>::const_iterator it1 = _shape.begin(); it1 != end; ++it1)
{
if (*it1 == *it || elementIncludedInVector(*it1, returnValue)) continue;
if (pointPositionRelativeToLine(returnValue.back(), *it, *it1) > 0.0f)
{
allPointWereToTheLeft = false;
break;
}
}
if (allPointWereToTheLeft)
{
returnValue.push_back(*it);
it = _shape.begin();
}
}
return returnValue;
}
這是我決定的功能其中一個線路的側的第三點是:
float pointPositionRelativeToLine(const sf::Vector2f& A, const sf::Vector2f& B, const sf::Vector2f& C)
{
return (B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x);
}
返回一個負數表示點是在一側上,正對其他,0表示這三個點是共線的。 現在,問題:如何修改上述代碼,使其即使在_shape中存在共線點時也能正常工作?
最遠的點不一定是所有其他點都在新形成的線的左側,導致錯誤。 –
離共線最遠! – MBo
這條規則非常正確。實際上,你實現了一個詞典對比:首先在角度上(通過簽名區域),然後在關係的情況下在距離上。 –