2013-08-05 63 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':無法從 '常量節點' 轉換 '這個' 指針 爲「節點&