本文介绍了std :: priority_queue包含带有函子的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用函子将结构 HeapNode 添加到 std :: priority_queue .

I want to add struct HeapNode to std::priority_queue using a functor.

#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 仍然感到困惑.

I have researched the reference but I'm still confused about std::priority_queue.

推荐答案

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

h designates an object with static storage duration. The priority_queue template expects a type. The error is quite clear on this:

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

现在,您将类型本身用作函子来进行比较有点奇怪(且效率低下).我建议将其拆分:

Now, it's a bit strange (and inefficient) that you use the type itself as a functor to compare it. I recommend splitting it:

struct HeapNode
{
    double c;     
    double v;     
};

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

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

Now your queue can be defined simply as such:

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


(1)我说效率低下,因为必须默认构造函子才能使用.您的类型具有占用存储空间的有意义状态.如果将类型本身用作函子,那会很浪费.单独的类型没有状态,并且将占用最少的存储空间.


(1) I say inefficient because a functor has to be default constructed in order to be used. Your type has meaningful state that occupy storage. If you use the type itself as a functor, that's a bit wasteful. The separate type has no state and will occupy minimal storage.

这篇关于std :: priority_queue包含带有函子的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 21:54