5

凸包を取得するプログラムを書いています。ポイントを極角で並べ替える必要があり、base前にポイントを選択したので、メンバー比較関数を作成します(オブジェクトごとにbaseポイントが異なることに注意してください)。しかし、それをに適用するとstd::sort、プログラムはコンパイルできません。

これが私のプログラムです:

class ConvexHull
{
  Point p[MAXN], base;
public:
  int size;
  void Create(Point (&)[MAXN], const int);
  bool cmp(const Point& a, const Point& b) const
  {
    static int tmp;
    return (tmp = CrossProduct(base, a, base, b)) < 0 || (tmp == 0 && Dist(base, a) < Dist(base, b));
  }
};
void ConvexHull::Create(Point (&a)[MAXN], const int n)
{
  base = a[0];
  for (int i = 1; i < n; ++i)
    if (a[i].x < base.x || (a[i].x == base.x && a[i].y < base.y))
      base = a[i];
  std::sort(a, a+n, cmp);
  p[0] = a[0], p[1] = a[1];
  size = 2;
  for (int i = 2; i < n; ++i)
  {
    while (size >= 2 && CrossProduct(a[i], p[size-1], a[i], p[size-2]) <= 0) --size;
    p[size++] = a[i];
  }
  p[size++] = p[0];
}

そしてここにエラーがあります:

poj1113.cc: In member function 'void ConvexHull::Create(Point (&)[1000], int)':
poj1113.cc:41:24: error: no matching function for call to 'sort(Point [1000], Point*, <unresolved overloaded function type>)'
poj1113.cc:41:24: note: candidates are:
In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from poj1113.cc:3:
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note: template<class _RAIter> void std::sort(_RAIter, _RAIter)
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note:   template argument deduction/substitution failed:
poj1113.cc:41:24: note:   candidate expects 2 arguments, 3 provided
In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from poj1113.cc:3:
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note: void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = Point*; _Compare = bool (ConvexHull::*)(const Point&, const Point&)const]
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note:   no known conversion for argument 3 from '<unresolved overloaded function type>' to 'bool (ConvexHull::*)(const Point&, const Point&)const'

それを修正する方法は?そして、これは(私はbaseメンバーを作ることを意味します)悪いデザインですか?

4

1 に答える 1

5

問題は、cmpメソッドがである必要があるということstaticです。その理由は、非静的メソッドは、目に見えない最初の引数であるthisポインターを予期しているためです。std::sort関数はこの余分な引数を渡しません。

メンバー変数を参照するため、関数を作成することはできませんが、staticこれを解決する方法は他にもあります。新しいC++11標準機能を使用することをお勧めしますstd::bind

std::sort(a, a+n, std::bind(&ConvexHull::cmp, this));

std::bind呼び出しは呼び出し可能なオブジェクトを作成し、最初のパラメーターをに設定して、呼び出さthisれたときに正しくなるようにします。

于 2012-12-10T12:55:24.570 に答える