Reputation: 7951
i have a priority queue and i have defined like this:
priority_queue<Node*,vector<Node*>,greater<Node*>> myQueue;
i have to add to queue on the basis of a parameter param and i have overloaded it like this
bool Node::operator>(const Node& right) const
{
return param>right.param;
}
since the overload function doesnt take a pointer object, how should i change it so that my overloaded function is called. i am adding to queue this way:
Node *myNode
myQueue.add(myNode);
i cant pass the myNode without making as pointer object. please guide ..
@Sellibitze i have done something like this
template<typename Node, typename Cmp = std::greater<Node> >
struct deref_compare : std::binary_function<Node*,Node*,bool>
{
deref_compare(Cmp const& cmp = Cmp())
: cmp(cmp) {}
bool operator()(Node* a, Node* b) const {
return cmp(*a,*b);
}
private:
Cmp cmp;
};
typedef deref_compare<Node,std::greater<Node> > my_comparator_t;
priority_queue<Node*,vector<Node*>,my_comparator_t> open;
i am filled with errors.
Upvotes: 1
Views: 1852
Reputation: 10142
The simplest way would be to implement a compare function that takes Node pointers as its parameters, like this:
bool nodePtrGreater(Node const *a, Node const *b) {
return *a > *b;
}
This function should use the operator> of your Node class properly.
[edit] The old version didn't define the queue correctly.
Create your priority queue like this:
priority_queue<Node*,vector<Node*>, bool(*)(Node const *, Node const *)> myQueue(nodePtrGreater);
Upvotes: 0
Reputation: 28097
You need to write your own functor for the comparison because you can't overload operator> for pointers. So, instead of greater you would be using your own dedicated class with the appropriate function call operator. This could be even done generically.
template<typename T, typename Cmp = std::less<T> >
struct deref_compare : std::binary_function<T const*,T const*,bool>
{
deref_compare(Cmp const& cmp = Cmp())
: cmp(cmp) {}
bool operator()(T const* a, T const* b) const {
return cmp(*a,*b);
}
private:
Cmp cmp;
};
typedef deref_compare<Node,std::greater<Node> > my_comparator_t;
Edit1: I just realized you could do it even more generically, with iterators instead of pointers. ;-)
Edit2: If you're not comfortable with the template and don't need this generalization you could just as well use
struct my_node_ptr_compare
{
bool operator()(Node const* a, Node const* b) const {
return *a > *b;
}
};
priority_queue<Node*,vector<Node*>,my_node_ptr_compare> foo;
Upvotes: 7
Reputation: 40319
Set up the operator>() as a friend-of-Nodes function taking two Nodes.
Use the friend
keyword.
Some refs:
http://www.cprogramming.com/tutorial/friends.html
http://msdn.microsoft.com/en-us/library/465sdshe(VS.80).aspx
Edit: This won't work in the pointer case, but will work in the regular Nodes case.
Upvotes: 1