簡體   English   中英

std :: priority_queue包含帶有函子的結構

[英]std::priority_queue contain struct with functor

我想使用函子將結構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仍然感到困惑。

您的priority_queue模板實例化的第三個參數是全局變量,而不是類型。 您聲明了struct HeapNode ,然后聲明了全局變量hstruct HeapNode類型。 在模板實例化struct HeapNode h替換為struct HeapNode

另外,我認為最好有一個單獨的比較器類,而不是重用您的節點類。 這是因為priority_queue將創建struct HeapNode的實例以具有比較器。

h指定一個具有靜態存儲持續時間的對象。 priority_queue模板需要一個type 錯誤很明顯:

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)我說效率低下,因為必須使用默認構造的函子才能使用。 您的類型具有占據存儲空間的有意義狀態。 如果將類型本身用作函子,那會很浪費。 單獨的類型沒有狀態,將占用最少的存儲空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM