如何按距离从点(x1,y1)以升序排列坐标组? [英] How to sort set of coordinates in ascending order by distance from point ( x1,y1)?

查看:138
本文介绍了如何按距离从点(x1,y1)以升序排列坐标组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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)以升序排列坐标组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆