代码之家  ›  专栏  ›  技术社区  ›  Ryan_IRL

需要STL排序算法的帮助

  •  1
  • Ryan_IRL  · 技术社区  · 15 年前

    我在使用std::sort算法时遇到一些问题。我在读到你可以重载小于运算符来对类排序,但是我得到了各种各样的错误。我还尝试使用了一个函数,如您在下面的示例中所看到的。

    我希望有人能看到我在这里做错了什么。

    #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 回复  |  直到 11 年前
        1
  •  3
  •   Alex Martelli    15 年前

    我相信你需要改变

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

    进入之内

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

    int val() {
    

    进入之内

    int val() const {
    

    注意,您的代码需要是常量正确的,并且不要求它修改事实上它不需要(也不需要)的东西。

        2
  •  4
  •   Paul    11 年前

    制作你的 val() operator<() const 功能。

    同样的 Sort::operator() 采取措施 const Thing& 而不是 Thing& .

        3
  •  0
  •   Nick Meyer    15 年前

    尝试使运算符<通过常量引用获取其参数。当您这样做时,您需要将其实现更改为直接访问(最好)make val()const(因为const成员函数不能调用非const函数)。