gls库,找到一个点和一组点之间的最小距离?

时间:2014-04-14 14:05:03

标签: c++ gsl

如何在c ++中使用gsl库找到点(X0,Y0)和一组点{P0,...,Pn}之间的最小距离? 我有一个多边形包含一组点{P0(X0,Y0),...,P(Xn,Yn)}和一个点C(X0,Y0), 我想计算C和点集之间的最小距离。

谢谢

1 个答案:

答案 0 :(得分:0)

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); });