std :: Priority_queue包含fuctor的结构

std::priority_queue contain struct with functor

本文关键字:fuctor 结构 包含 queue Priority std      更新时间:2023-10-16

我想使用函数将 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

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(我说效率低下,因为必须构建函数才能使用才能使用。您的类型具有有意义的状态,可以占据存储。如果您将类型本身用作函子,那有点浪费。单独的类型没有状态,将占据最小存储。

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

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