我有一个类,其中包含指向对象的指针列表,需要使用比较器进行排序,比较器是该类的成员:
class VoronoiDiagram
{
public:
void BuildVoronoi();
private:
list<shared_ptr<QPointF>> inputPoints
QPointF currentVoronoiPoint;
bool compairingPointsPredictate(shared_ptr<QPointF> a, shared_ptr<QPointF> b) { float d1 = (a->x()-currentVoronoiPoint.x())*(a->x()-currentVoronoiPoint.x()) + (a->y()-currentVoronoiPoint.y())*(a->y()-currentVoronoiPoint.y());
float d2 = (b->x()-currentVoronoiPoint.x())*(b->x()-currentVoronoiPoint.x()) + (b->y()-currentVoronoiPoint.y())*(b->y()-currentVoronoiPoint.y());
return d1 < d2; };
};
我在BuildVoronoi()中调用了这个:
inputPoints.sort(compairingPointsPredictate);
但这给了我两个错误:C3867与我的比较器功能和C2660与std :: list :: sort(不接收1参数)。
对不起我的英文或解释。我真的希望有人可以帮助我。感谢。
答案 0 :(得分:2)
sort
需要一个两个参数比较函数,但作为成员函数的声明会产生类似于的调用:
a.compairingPointsPredicate( b, c)
// ^
// no 't', it is predicate not predictate ;p
没有理由让compairingPointsPredicate成为一个类的成员。您可以使其成为一个独立的功能(如果需要访问私人数据,则为QPointF的朋友)。
class QPointF{
friend bool compairingPointsPredicate(
shared_ptr<QPointF> a, shared_ptr<QPointF> b);
};
bool compairingPointsPredicate(shared_ptr<QPointF> a,
shared_ptr<QPointF> b) {
float d1 = (a->x()-currentVoronoiPoint.x())
*(a->x()-currentVoronoiPoint.x()) +
(a->y()-currentVoronoiPoint.y())
*(a->y()-currentVoronoiPoint.y());
float d2 = (b->x()-currentVoronoiPoint.x())
*(b->x()-currentVoronoiPoint.x()) +
(b->y()-currentVoronoiPoint.y())
*(b->y()-currentVoronoiPoint.y());
return d1 < d2;
}
用法:
inputPoints.sort(compairingPointsPredicate);