how to make object sortable for use in STL containers

W

Wiseguy

Hi.

I'm having a bit of trouble overriding operators necessary to make my
classes work in sorted STL containers.

I'm getting a most obnoxious compiler error about negated qualifiers.

Can someone point me in the right direction based on my attached code?

// ---------------------------------------------------------------
#include <set>
using namespace std;
struct Things {
int x,y;
Things(int a,int b): x(a),y(b);
const bool operator<(const Things& r) { return (x*y)<(r.x*r.y); }
/* The previous operator generates the following compiler error
based trying to insert objects with t.insert(Things(a,b))
t.cpp:22: instantiated from here
/usr/local/include/c++/3.3/bits/stl_function.h:197: error: passing
`const Things' as `this' argument of `const bool
Things::eek:perator<(const Things&)' discards qualifiers
*/
};
typedef set<Things> SetOfThings;
int main() {
SetOfThings t;
t.insert(Things(1,5));
return 0;
}
// -------------------------------------------------------------

I tried wrapping the operator in a class to replace the less<>
template but the end result is that sooner or later it has to
execute my overridden < operator and the error occurs.

Any suggestions (other than a google search)...I'm using gcc 3.3
 
J

Jerry Coffin

Wiseguy said:
const bool operator<(const Things& r) { return (x*y)<(r.x*r.y); }

Try:

bool operator<(const Things &r) const { return x*y < r.x * r.y; }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top