C++ 在类中比较std::sort can';不编译
我正在写一个程序来得到一个凸包。我需要按极轴角度对点进行排序,之前我选择了一个C++ 在类中比较std::sort can';不编译,c++,sorting,stl,C++,Sorting,Stl,我正在写一个程序来得到一个凸包。我需要按极轴角度对点进行排序,之前我选择了一个base点,因此我编写了一个成员比较函数(注意,对于每个对象,base点是不同的)。但是当我将其应用于std::sort时,程序无法编译 这是我的节目: class ConvexHull { Point p[MAXN], base; public: int size; void Create(Point (&)[MAXN], const int); bool cmp(const Point&am
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];
}
class ConvxHull
{
点p[MAXN],基准;
公众:
整数大小;
无效创建(点(&)[MAXN],常数int);
布尔cmp(常数点a、常数点b)常数
{
静态int-tmp;
返回(tmp=CrossProduct(base,a,base,b))<0 | |(tmp==0&&Dist(base,a) 虽然(size>=2&&CrossProduct(a[i],p[size-1],a[i],p[size-2])问题是cmp
方法需要是静态的。原因是非静态方法需要一个不可见的第一个参数,这个指针。std::sort
函数不传递这个额外的参数
由于引用了成员变量,因此无法使函数成为静态的
,但还有其他方法可以解决此问题。我建议使用新的C++11标准功能:
std::bind
调用创建一个可调用的对象,将第一个参数设置为this
,这样调用时它将是正确的。您不需要将数组作为引用传递给Create
函数,除非您计划分配给实际变量,例如a=foo
。但我需要基
,哪一个是类成员。?你不需要它成为类成员,制作一个全局函数bool Compare(const point&base,const point&p1,const point&p2)
并使用boost::bind或C++11 lambdas“修复”第一个参数。@AlexanderChertov-aha,这真是一个更好的设计。
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'
std::sort(a, a+n, std::bind(&ConvexHull::cmp, this));