Connecting Tech Pros Worldwide Help | Site Map

how to make object sortable for use in STL containers

 
LinkBack Thread Tools Search this Thread
  #1  
Old July 23rd, 2005, 02:00 AM
Wiseguy
Guest
 
Posts: n/a
Default how to make object sortable for use in STL containers

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, 02:00 AM
Jerry Coffin
Guest
 
Posts: n/a
Default 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.

 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,989 network members.