我有一个std :: list,我正在尝试根据一些计算进行排序。 Point2D是只有int no,double x和double y的结构;

这是包含我的list.sort代码的方法:

std::vector<Point2D> GrahamScan::getSortedPointSet(std::vector<Point2D> points) {
Point2D lowest = getLowestPoint(points);

std::list<Point2D> list;

for (int i = 0; i < (int)points.size(); i++) {
    list.push_back(points[i]);
}

list.sort(compare_points);

std::vector<Point2D> temp;
for (int i = 0; i < (int)list.size(); i++) {
    temp.push_back(list.front());
    list.pop_front();
}
return temp;
}


这是我写的compare_points方法:

bool GrahamScan::compare_points(const Point2D& a, const Point2D& b) {
if (a.x == b.x && a.y == b.y) {
    return false;
}

double thetaA = atan2((long)a.y - lowest.y, (long)a.x - lowest.x);
double thetaB = atan2((long)b.y - lowest.y, (long)b.x - lowest.x);

if (thetaA < thetaB) {
    return false;
}
else if (thetaA > thetaB) {
    return true;
}
else {
    double distanceA = sqrt((((long)lowest.x - a.x) * ((long)lowest.x - a.x)) +
        (((long)lowest.y - a.y) * ((long)lowest.y - a.y)));
    double distanceB = sqrt((((long)lowest.x - b.x) * ((long)lowest.x - b.x)) +
        (((long)lowest.y - b.y) * ((long)lowest.y - b.y)));

    if (distanceA < distanceB) {
        return false;
    }
    else {
        return true;
    }
}
}


Visual Studio向我吐出的错误是“ GrahamScan :: compare_points”:非标准语法;使用“&”创建指向成员的指针”

我没有太多的C ++经验,但是我试图将一些使用TreeSet的Java代码转换为C ++,这是我的尝试。

任何援助将不胜感激。

最佳答案

如果要将compare_points保留在GrahamScan命名空间中,则需要使其保持静态:

static bool GrahamScan::compare_points


编译器抱怨的原因是compare_points是成员函数。它需要应用一个GrahamScan对象。幕后的compare_points真正功能签名类似于bool compare_points(GrahamScan *this, const Point2D& a, const Point2D& b)。因此,要么将其设为静态,要么不将其定义为成员函数。

一旦将compare_points设置为静态,最低变量将不再可访问。解决此问题的更简单方法是使最低设置也保持静态:

class GrahamScan
{
    // declaration is inside class
    static Point2D lowest;
}

// definition is outside class
Point2D GrahamScan::lowest;


并像这样使用它:

std::vector<Point2D> GrahamScan::getSortedPointSet(std::vector<Point2D> points)
{
    GrahamScan::lowest = getLowestPoint(points);
    //...
}

10-06 05:17