我在這裏使用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;
}
它是`operator <()`而不是`opeartor <()`。由於修復太小,我無法編輯它。 – lucas92 2013-12-12 16:49:01