我有 std :: set< std :: pair< float,float>> 它代表地图上的点(2d,x和y值)一个值为x1和y1。如何按照距离点(x1,y1)的升序排序?
I have std::set<std::pair<float,float>> which represents points on map ( 2d , x and y value) and I have one point with values x1 and y1. How to sort set in ascending order by distance from point ( x1,y1) ?
推荐答案std :: set 是一个有序容器,并且在插入时发生排序,这取决于可以指定的排序标准第二模板参数。所以使用 set 和根据到参考点的距离返回true或false的谓词。
std::set is an ordered container, and ordering happens upon insertion, depending on a sorting criteria which can be specified with a second template argument. So use a set with a predicate which returns true or false based on the distance to the reference point.
struct DistanceCompare { DistanceCompare(const std::pair<float,float>& point) : point_(point) {} bool operator()(const std::pair<float,float>& lhs, const std::pair<float,float>& rhs) const { return distance2(lhs) < distance2(rhs); }; private: float distance2(const std::pair<float,float>& point) const { // calculate distance squared between point and point_ const float x = point.first - point_.first; const float y = point.second - point_.second; return x*x + y*y; } std::pair<float, float> point_; }; .... std::pair<float,float> refPoint = ....; DistanceCompare comp(refPoint); std::set<std::pair<float, float>, DistanceCompare> pointSet(comp);这足以比较距离的平方,从而避免调用 std: :sqrt 。
It is enough to compare the distance squared, thus avoiding calls to std::sqrt.
更多推荐
如何按距离从点(x1,y1)以升序排列坐标组?
发布评论