2009-07-09 81 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成为可能。