如何创建节点结构类型的Min stl priority_queue

时间:2013-03-26 17:12:01

标签: c++ c vector stl priority-queue

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

这是我的struct节点。 现在我使用stl优先级队列来提取min,即优先级队列中的最小值,如此

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

但我没有得到最小值和谷歌搜索,我发现(更大),它用于整数,我得到了另一个答案,我实现了这样

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

我就像这样使用

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

但它显示错误我感到沮丧,任何人帮助我

3 个答案:

答案 0 :(得分:3)

比较函数应该采用两个参数,这两个参数是优先级队列中元素的类型。您的元素类型为node*,因此您的函数应定义为bool operator()(node* l, node* r)。现在,您可以将比较函数考虑在内:

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

假设您想使用结构的data字段进行比较,这种类型的仿函数应该可以工作:

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

bool operator()const,因为调用它不应更改其状态。 C ++标准不要求它是const方法,但某些实现可能需要它,导致编译错误。

相关问题