Problem using std::set

Member
Posts: 61
Joined: 2007.01
Post: #1
Hi,

I'm trying to use a set to store classes (Messages) because it will sort them (based on the time they should be sent) and also prevent any duplicates.

However, I'm having trouble to get the 'operator<'

I've written it as a member function of my Message class because I figured set would look there to call it, but I get the following error:

Code:
error: no match for 'operator<' in '__x < __y'
note: candidates are: bool Message::operator<(Message&)

I've tried to write the function as close to the described way:

Code:
template <class _Tp>
    struct less : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x < __y; }
    };

But when I do that I'm told my function (operator<(const Message &m1, const Message &m2) ) must only take ONE argument.

This is my attempt at overloading:

Code:
inline bool Message::operator<(Message &m2)
{
    if (*this == m2)
    {
        return false;
    }
    else
    {
        return  (GetDispatchTime() < m2.GetDispatchTime());
    }
}

Any ideas?

Thanks

Anthony
Quote this message in a reply
Member
Posts: 61
Joined: 2007.01
Post: #2
I fixed the problem!

I moved both operators into the Header file and changed them to

Code:
inline bool operator==(const Message &m1, const Message &m2)
{
...
}

inline bool operator<(const Message &m1, const Message &m2)
{
...
}

It works...I'll figure out how a bit better later on!

I guess though in future it makes better sense to avoid using member functions for binary operations like that - friend / non-member functions instead.
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #3
My understanding is that the STL prefers comparison operators to be in this form. I'm not enough of a C++ guru to be able to say why, however.
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #4
If you add a couple of "const"s to the operators when they're member functions they should work that way too.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #5
To clarify on what OSC said, you need to put a cosnt after the parameter list to tell the compiler "this" will not be changed. For example
Code:
class Bla
{
public:
   //stuff
   bool operator<(const Bla &other) const
   {
      //code
   }
};
Quote this message in a reply
Member
Posts: 61
Joined: 2007.01
Post: #6
Thanks for the replies! Smile

Quote:To clarify on what OSC said, you need to put a cosnt after the parameter list to tell the compiler "this" will not be changed.

That makes a lot of sense now actually, as I was getting an error about passing "this" being made invalid - I just can't remember off the top of my head what the exact words in the error were.
Quote this message in a reply
Post Reply