Rajesh M
Rajesh M

Reputation: 634

How can I create Min stl priority_queue of node structure type

struct node
{
node *right;
node *left;
int data;   
};

This is my struct node. Now I am using stl priority queue in order to extract min i.e the minimum from the priority queue like this

    std::priority_queue<node*, std::vector<node*>, std::greater<node*> > mypq;

But I am not getting the minimum and googled and I found that (greater), It is used for integers and I got another answer and I implemented like this

 struct compare  
 {  
 bool operator()(const node*& l, const node*& r)  
  {  
   return l > r;  
   }  
 };  

And I used like this

  std::priority_queue<node*, std::vector<node*>,compare > mypq;

But it is showing errors I am frustrated, Any body help me please

Upvotes: 2

Views: 1096

Answers (3)

juanchopanza
juanchopanza

Reputation: 227608

Assuming you want to compare using the data fields of the struct, this type of functor should work:

struct compare  
{  
  bool operator()(const node* l, const node* r)  const
  {  
    return l->data > r->data;  
  }  
};

where the bool operator() is const because calling it should not change its state. It is not required by the C++ standard that it be a const method, but some implementations may require it, resulting in compilation errors.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

The comparison function should take two arguments that are the type of the elements in the priority queue. The types of your elements are node*, so your function should be defined as bool operator()(node* l, node* r). Now, you can write the comparison function taking this into account:

struct compare  
{  
  bool operator()(node* l, node* r)  
  {  
    return l->data > r->data;  
  }  
};  

Upvotes: 3

gongzhitaao
gongzhitaao

Reputation: 6682

struct compare  
 {  
 bool operator()(const node*& l, const node*& r)  
  {  
   return l->data > r->data;  
   }  
 };

Upvotes: 2

Related Questions