Re: Q: STL priority_queue with boost shared_ptr
zl2k wrote:
hi, all
Here is what I want to do: to wrap my self defined class in a
shared_ptr and then insert it into the priority_queue. The
priority_queue should pump the least element of the self defined class
first. To make it simple, here is the toy code.
bool operator<(const myClass & right) const { //the comparison is
"reversed" in order to pop smallest first
return a > right.a;
};
Okay, look's fine.
priority_queue<shared_ptr<myClass> > pq;
Oops. You are using shared_ptr's operator<, not the one in myClass.
I was expecting the priority_queue to pop 1 first and 3 last. However,
it pops 3 first and 1 last.
You need to define a function object that does the comparison you want
when given two shared_ptr's. Example:
struct ptr_less
{
bool operator()(const shared_ptr<myClass> & lhs,
const shared_ptr<myClass> & rhs)
{
return *lhs < *rhs ;
}
} ;
Or, if you want to be a bit more reusable, you could generalize this to
any type that can be dereferenced into a type that defines operator<.
Defining your priority_queue gets considerably more fun now. The second
template parameter is the container type. By default this is vector<T>,
so unless you have a reason just stick with that:
priority_queue<shared_ptr<myClass>,vector< shared_ptr<myClass> >,
ptr_less< shared_ptr<myClass> > > pq;
You might consider some typedefs to make that more readable.
--
Alan Johnson