views:

308

answers:

3

I'm having some troubles with using the std::sort algorithm here. I was reading that you can just overload the less than operator to sort classes, but I have been getting all sorts of errors. I have also tried using a functor as you can see in the example I made below.

I was hoping somebody could see what I'm doing wrong here.

#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  A: 

Make your val() and opeartor<() const functions.

The same for Sort::operator()take const Thing& instead of Thing&.

Paul
+3  A: 

I believe you need to change

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

into

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

and

int val() {

into

int val() const {

IOW, your code needs to be const-correct and not claim it may modify things it in fact doesn't (nor needs to).

Alex Martelli
A: 

Try making operator< take its argument by const reference. You'll need to change its implementation to directly access _val or (preferably) make val() const as well when you do this (because a const member function can't call a non-const one).

Nick Meyer