3

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(){
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.

Community
  • 1
  • 1
thomast.sang
  • 181
  • 1
  • 2
  • 4

2 Answers2

6

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.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
1

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.

Fabian Giesen
  • 3,231
  • 16
  • 16
  • 25.3/2: "It is assumed that `comp` will not apply any non-constant function through the dereferenced iterator". GCC is assuming it pretty actively ;-) – Steve Jessop Nov 03 '10 at 04:19