I've been having issues with STL sort. I'm trying to sort a vector of objects by a data member in the object. I've looked up several examples, but once it falls into my configuration it somehow doesn't compile under GCC. I tested on Visual Studio and it works. I get this error on GCC:
no match for call to '(test::by_sym) (const stock&, const stock&)
What I don't understand is that the same code will compile on Visual Studio.
Here's my set up.
driver.cpp
DB t1;
t1.print();
cout << "---sorting---" << endl;
t1.sSort();
t1.print();
class DB
vector<stock> list;
struct by_sym {
bool operator()(stock &a, stock &b) {
return a.getSymbol() < b.getSymbol();
}
};
void DB::sSort(开发者_JAVA百科){
std::sort(list.begin(), list.end(), by_sym());
}
and my stock class just has the data members.
Is there a workaround on GCC?
I believe my question is similar to this, but the solutions on there are not working for me.
Your operator()()
is const-incorrect. Change it to
bool operator()(const stock& a, const stock& b) const
Make sure stock::getSymbol()
is also a const
function. If it isn't and you can't change it then take the parameters of operator()()
by value, not by (const) reference.
The error message says it all - apparently the G++ STL implementation expects a comparison predicate to take const arguments. Try changing the declaration of operator() to
bool operator()(const stock &a, const stock &b)
and check if it helps.
精彩评论