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;
}