2009-07-09 78 views
1

我在這裏使用std :: sort算法時遇到了一些麻煩。我在讀,你可以重載少於運算符來排序類,但我一直在得到各種各樣的錯誤。我也嘗試過使用仿函數,正如你在下面的例子中看到的那樣。STL排序算法需要幫助

我希望有人能看到我在這裏做錯了什麼。

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

#include <stdlib.h> 
#include <time.h> 

class Thing { 
public: 
    Thing(int val) { 
     this->_val = val; 
    } 

    bool operator<(Thing& rhs) { 
     std::cout << "this works!"; 
     return this->val() < rhs.val(); 
    } 

    int val() { 
     return this->_val; 
    } 
protected: 
    int _val; 
}; 

struct Sort { 
    bool operator()(Thing& start, Thing& end) { 
     return start.val() < end.val(); 
    } 
}; 

int main (int argc, char * const argv[]) { 
    std::srand(std::time(NULL)); 

    std::vector<Thing> things; 
    for(int i = 0; i < 100; i++) { 
     Thing myThing(std::rand()); 
     things.push_back(myThing); 
    } 

    if(things[1] < things[2]) { 
     //This works 
    } 

    //std::sort(things.begin(), things.end()); //This doesn't 

    //std::sort(things.begin(), things.end(), Sort()); //Neither does this 

    for(int i = 0; i < 100; i++) { 
     std::cout << things.at(i).val() << std::endl; 
    } 

    return 0; 
} 

回答

3

我相信你需要改變

bool operator()(Thing& start, Thing& end) { 

bool operator()(const Thing& start, const Thing& end) { 

int val() { 

int val() const { 

IOW,你的代碼需要是const正確的,而不是聲稱它可能會修改它實際上不需要的東西(也不需要)。

4

讓您val()operator<()const功能。

Sort::operator()相同 - 取const Thing&而不是Thing&

+0

它是`operator <()`而不是`opeartor <()`。由於修復太小,我無法編輯它。 – lucas92 2013-12-12 16:49:01

0

試着讓運算符<通過const引用取其參數。當你這樣做時(因爲const成員函數不能調用非const函數),你需要改變它的實現來直接訪問_val或(最好)使val()const成爲可能。