std :: priority_queue包含带有仿函数的struct

时间:2017-06-28 06:33:32

标签: c++ data-structures std

我想使用仿函数将HeapNode添加到std::priority_queue

#include <iostream>
#include <queue>
#include <algorithm>   

using namespace std;

struct HeapNode
{
    bool operator()(const struct HeapNode &a,const struct HeapNode &b) const 
    {  
        return b.c>=a.c;  
    } 
    double c;     
    double v;     
}h;

int main()
{
    priority_queue<struct HeapNode,vector<struct HeapNode>,h> H;
    struct HeapNode a={1,2};
    struct HeapNode b={3,2};
    struct HeapNode c={6,2};
    H.push(a);
    H.push(b);
    H.push(c);
}

但有错误:

queue.cpp: In function ‘int main()’:
queue.cpp:19:65: error: type/value mismatch at argument 3 in template parameter list for ‘template<class _Tp, class _Sequence, class _Compare> class std::priority_queue’
  priority_queue<struct HeapNode,vector<struct HeapNode>,heapnode> H;
                                                                 ^
queue.cpp:19:65: note:   expected a type, got ‘heapnode’
queue.cpp:23:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
  H.push(1);
    ^
queue.cpp:24:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
  H.push(2);
    ^
queue.cpp:25:4: error: request for member ‘push’ in ‘H’, which is of non-class type ‘int’
  H.push(3);
    ^

我已经研究了参考文献,但我仍然对std::priority_queue感到困惑。

2 个答案:

答案 0 :(得分:0)

priority_queue模板实例化的第三个参数是全局变量,而不是类型。 您声明了struct HeapNode,然后声明全局变量hstruct HeapNode类型。在模板实例化中将h替换为struct HeapNode

另外,我认为最好有一个单独的比较器类而不是重用你的节点类。这是因为priority_queue将创建struct HeapNode的实例以使用比较器。

答案 1 :(得分:0)

h指定具有静态存储持续时间的对象。 priority_queue模板需要类型。错误很明显:

error: type/value mismatch at argument 3 in template parameter list

现在,你使用类型本身作为函子来比较它有点奇怪(并且效率低下)(1)。我建议拆分它:

struct HeapNode
{
    double c;     
    double v;     
};

struct HeapNodeCompare
{
    bool operator()(const struct HeapNode &a,const struct HeapNode &b) const 
    {  
        return b.c>=a.c;  
    } 
};

现在您的队列可以简单地定义:

priority_queue<HeapNode, vector<HeapNode>, HeapNodeCompare> H;

(1)我说效率低,因为必须默认构造仿函数才能使用。您的类型具有占用存储空间的有意义状态。如果你使用类型本身作为仿函数,这有点浪费。单独的类型没有状态,占用的存储空间很小。