【问题标题】:Need help with STL sort algorithm在 STL 排序算法方面需要帮助
【发布时间】:2009-07-09 15:24:18
【问题描述】:

我在这里使用 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;
}

【问题讨论】:

    标签: c++ algorithm stl sorting


    【解决方案1】:

    制作您的 val()operator&lt;() const 函数。

    Sort::operator() 也一样——使用 const Thing&amp; 而不是 Thing&amp;

    【讨论】:

    • 它是 operator&lt;() 而不是 opeartor&lt;()。我无法编辑它,因为修复太小了。
    【解决方案2】:

    我相信你需要改变

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

    进入

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

    int val() {
    

    进入

    int val() const {
    

    IOW,您的代码需要是 const 正确的,并且不要声称它可能会修改它实际上没有(也不需要)的东西。

    【讨论】:

      【解决方案3】:

      尝试让 operator

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 2011-08-06
        • 1970-01-01
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多