2015-09-02 60 views
0

我試圖使用stable_sort將一個向量指針stable_sort in C++

排序到某個類。我有一個這樣的代碼:

#include <iostream> 
#include <vector> 
#include <algorithm> 

using namespace std; 

class B 
{ 
    public : 
     B(int y, int j) {x = y, r = j;}; 

     void getVal() {cout << x << endl; }; 

     int x; 
     int r; 
}; 


bool compareB(B* b1, B* b2) 
{ 
    return b1->getVal() < b2->getVal(); 
} 

int main() 
{ 
    B b1(3, 4), b2(-5, 7), b3(12, 111); 

    vector<B*> myVec; 
    myVec.push_back(&b1); 
    myVec.push_back(&b2); 
    myVec.push_back(&b3); 

    std::stable_sort(myVec.begin(), myVec.end(), compareB); 
    for (size_t size = 0; size < myVec.size(); ++size) 
    { 
     myVec[size]->getVal(); 
    } 

    return 0; 
} 

不過,我得到了foolowing錯誤,而它編譯:

「錯誤:類型‘無效’和‘無效’二進制‘操作<’無效操作數 return b1-> getVal()< b2-> getVal();「

有人可以幫助我嗎?

+3

你'getVal'返回'void'。也許應該是'int'? –

+2

...並且實際返回值而不是僅打印它。 –

回答

4

問題是與

void getVal() {cout << x << endl; }; 

它返回void,而不是一定價值。

當你在return b1->getVal() < b2->getVal();中使用它時,它歸結爲return void < void;,它不會編譯。

你應該能夠將其更改爲

int getVal() { return x; };