2013-08-05 65 views
0

我想排序我存储在一个向量中的C++中的一些节点。排序向量的指针

bool compare_func(const node* a, const node* b) 
{ 
    return a->getPoint()<b->getPoint(); 
} 

其中,getPoint()返回一个浮点数,我想用它来排序我的矢量。

然而,当我运行它:

std::sort(dataSet.begin(), dataSet.end(), compare_func); 

我得到:提前

using namespace std; 
std::vector<node*> dataSet; 

感谢:

error C2662: 'node::getStartPoint' : cannot convert 'this' pointer from 'const node' to 'node & 
error C2662: 'node::getStartPoint' : cannot convert 'this' pointer from 'const node' to 'node &' 
error C2039: 'sort' : is not a member of 'std' 
error C3861: 'sort': identifier not found 

我有这个在我的文件的顶部!

更新: 我重载了getPoint函数,并且确实忘记了算法include,[我原以为我已经将它包含在一点]。

谢谢!

+1

是'getPoint'和任何其他功能,它使用'const'-合格吗? – Nbr44

+1

您发布的代码并不涉及'getStartPoint',因此它可能是错误的或不完整的。不管你想调用什么方法,都需要被const限定。 – Useless

回答

1

看起来你需要提供const超载node::getPoint()

struct node 
{ 
    ... 
    SomePoint getPoint() const { return .... ; } 
    //     ^^^^^ 
}; 

除此之外,你需要包括<algorithm>报头std::sort

4

前两个错误看起来像是在const对象上调用getStartPoint(),而成员函数不是const。为了解决这个问题:

point getStartPoint() const; 
         ^^^^^ 

第二两个是因为你还没有包括声明std::sort头:

#include <algorithm> 
0
#include <algorithm> 

并声明你的函数为const

point getStartPoint() const; 

因为你在const node上调用它,只有声明了const的函数可能会在co上调用nst对象。这样的功能不能改变任何班级成员(除非声明为mutable)。

声明一个成员方法会产生一个函数声明,它将成员指针作为第一个参数。 例如:

class node{ 
public: 
    point getStartPoint(); 
    point getStartPoint(int arg); 
}; 

导致

point node::getStartPoint(node* this); 
point node::getStartPoint(node* this, int arg); 

但:

class node{ 
public: 
    point getStartPoint() const; 
    point getStartPoint(int arg) const; 
}; 

导致

point node::getStartPoint(const node* this); 
point node::getStartPoint(const node* this, int arg); 

因此错误

错误C2662: '节点:: getStartPoint':无法从 '常量节点' 转换 '这个' 指针 为“节点&