Stephen Horne
10/13/2008 8:52:00 AM
On Mon, 13 Oct 2008 02:34:04 +0000, "Joe, G.I."
<invalid.email@address> wrote:
> // Not sure what I'm doing here, but I'm trying to do an overload
> // operator and have it return the priority of the smallest time. I
> // think this is where I need help.
> // Not even sure if this is the thing to do.
>
> bool MyEvent::operator < (const MyEvent *event)
> {
> if (_timestamp < event->_timestamp())
> return true;
> }
>
> return false;
> }
Don't do this - you're trying to overload a pointer comparison.
One option is the functor described by Kai-Uwe Bux. Another option is
to create a wrapper class for your items. Define operator< for that
class. For example...
struct MyEventThingy
{
MyEvent* m_Value;
bool operator< (const MyEventThingy &p) const
{
return (m_Value->timestamp > p.m_Value->timestamp);
}
};
IIRC, std::priority_queue always gives you the highest value item
next. Since you want the lowest timestamp, the operator< uses reverse
logic.
This done, you can use std::priority_queue<MyEventThingy>.
The functor approach has significant advantages, of course, especially
if you have different containers containing the same kinds of items,
but with different orderings. This not necessarily a good alternative,
just an alternative.
BTW - are you from a more Java / C# background?
Just asking because of the line...
pq = new MyPriorityQueue();
In C++, you can just write...
MyPriorityQueue localvarname ();
And this is preferred in general because it avoids allocating memory
from the heap, ensures proper cleanup when the object goes out of
scope, etc. You *may* have good reason for using a pointer, but it
seems a little odd.