2

マップ上のポイント ( 2d 、 x および y 値)をstd::set<std::pair<float,float>>表すものと、値 x1 および y1 を持つ 1 つのポイントがあります。ポイント ( x1,y1) からの距離でセットを昇順にソートする方法は?

4

2 に答える 2

6

std::setは順序付きコンテナーであり、2 番目のテンプレート引数で指定できる並べ替え基準に応じて、挿入時に順序付けが行われます。setそのため、基準点までの距離に基づいて true または false を返す述語でa を使用します。

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

距離の 2 乗を比較するだけで十分なため、 の呼び出しを回避できますstd::sqrt

于 2012-09-17T09:10:08.220 に答える
-1

The distance between two points can be calculated as follows:

xd = x2-x1;
yd = y2-y1;
Distance = SquareRoot(xd*xd + yd*yd);

And the value of Distance can be used as sorting parameter.

于 2012-09-17T09:13:03.623 に答える