Connecting Tech Pros Worldwide Help | Site Map

how to make object sortable for use in STL containers

  #1  
Old July 23rd, 2005, 03:00 AM
Wiseguy
Guest
 
Posts: n/a
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::operator<(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


----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
  #2  
Old July 23rd, 2005, 03:00 AM
Jerry Coffin
Guest
 
Posts: n/a

re: how to make object sortable for use in STL containers


Wiseguy wrote:
[color=blue]
> const bool operator<(const Things& r) { return (x*y)<(r.x*r.y); }[/color]

Try:

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

--
Later,
Jerry.

The universe is a figment of its own imagination.

Closed Thread