PDA

View Full Version : Problem using std::set


anthony
2007.07.17, 04:44 PM
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:


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:


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:


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


Any ideas?

Thanks

Anthony

anthony
2007.07.17, 05:07 PM
I fixed the problem!

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



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.

TomorrowPlusX
2007.07.17, 05:24 PM
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.

OneSadCookie
2007.07.17, 07:34 PM
If you add a couple of "const"s to the operators when they're member functions they should work that way too.

akb825
2007.07.17, 11:35 PM
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

class Bla
{
public:
//stuff
bool operator<(const Bla &other) const
{
//code
}
};

anthony
2007.07.18, 04:56 AM
Thanks for the replies! :)

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.