PDA

View Full Version : C++ Sorting Objects STL


linchear
2006.10.06, 03:10 PM
Hi I'm trying to port code over from visual C++ to GCC, but I find that I'm having trouble sorting objects in a vector.

I have trouble compiling this code with GCC, but it works fine for me in VC++.


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

class cHash{
int key;
double value;
public:

bool operator<(const cHash &a){
double v;
cHash a1=a;
v=a1.getValue();
return value<v;

}

double getValue();
int getKey();

void setKey(int k);
void setValue(double v);
};



int main(void){
vector<cHash> v1;

cHash c;
c.setKey(0);
c.setValue(1);

v1.push_back(c);

c.setKey(1);
c.setValue(2);
v1.push_back(c);

sort(v1.begin(),v1.end());

return 0;
}



I've googled my brains out, and can't seem to find a good example.

akb825
2006.10.06, 03:26 PM
What errors does it give?

linchear
2006.10.06, 03:29 PM
Sorry for leaving that out:


error: passing "const cHash" as "this" argument of "bool cHash::operator<(const cHash&)" discards qualifiers


I get the same error in OS X G++ and Linux as well.

I've tried different things versions, removing the const &... same error. It's got to be something simple I'm overlooking.

linchear
2006.10.06, 04:32 PM
I found out why.

I need to have:


bool cHash::operator <(const cHash &a) const{

return value< a.value;
}


as the operator overload for it to work in GCC.