【问题标题】:How can I create Min stl priority_queue of node structure type如何创建节点结构类型的 Min stl priority_queue
【发布时间】:2013-03-26 17:12:01
【问题描述】:
struct node
{
node *right;
node *left;
int data;   
};

这是我的结构节点。 现在我正在使用 stl 优先级队列来提取最小值,即像这样从优先级队列中提取最小值

    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;

但它显示错误我很沮丧,请任何人帮助我

【问题讨论】:

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


    【解决方案1】:

    比较函数应该接受两个参数,它们是优先级队列中元素的类型。你的元素的类型是node*,所以你的函数应该定义为bool operator()(node* l, node* r)。现在,您可以在考虑到这一点的情况下编写比较函数:

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

    【讨论】:

      【解决方案2】:
      struct compare  
       {  
       bool operator()(const node*& l, const node*& r)  
        {  
         return l->data > r->data;  
         }  
       };
      

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2011-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-20
          • 1970-01-01
          • 2019-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多