如何使用c ++中的gsl库找到一个点(X0,Y0)与一组点{P0,...,Pn}之间的最小距离?
我有一个包含一组点{P0(X0,Y0),...,P(Xn,Yn)}和一个点C(X0,Y0)的多边形,
我想计算C与点集之间的最小距离。
谢谢
最佳答案
double min_dist = DBL_MAX; // some large number
Point pointC; // set this to the point you want to compare
vector<Point> pointList; // push_back all your points
for (auto it = pointList.begin(); it != pointList.end(); ++it)
{
Point tempPoint = *it;
// Calculate distance between C and current point
double newDist = sqrt(pow((tempPoint.x - pointC.x),2) + pow((tempPoint.y - pointC.y),2))
// Update min_dist if necessary
min_dist = min(min_dist, newDist)
}
使用某些C ++ 11功能,可以将其编写为
double min_dist = *std::min_element(begin(pointList),
end(pointList),
[pointC](const Point& lhs, const Point& rhs){ return std::hypot(lhs.x - pointC.x, lhs.y - pointC.y) < std::hypot(rhs.x - pointC.x, rhs.y - pointC.y); });