[英]Errors when pushing structure object in boost::heap::priority_queue
我有一個結構,其對象將被推入boost::heap::priority_queue
。
typedef struct
{
int i, j;
double deltaQ;
} heapNode;
int main()
{
double a[] = {0.03, 0.01, 0.04, 0.02, 0.05};
heapNode node;
boost::heap::priority_queue<heapNode> maxHeap;
for(int i = 0; i < 5; i++)
{
node.deltaQ = a[i];
node.i = i;
node.j = i;
maxHeap.push(node);//error
}
for(int i = 0; i < 5; i++)
{
node = maxHeap.top();
cout << node.deltaQ << " " << node.i << " " << node.j;
cout << "\n";
maxHeap.pop();
}
}
此代碼給出了一個編譯器錯誤,
error: no match for 'operator<' (operand types are 'const heapNode' and 'const heapNode')|
任何解決方案,我使用的是codeBlocks 16.01。
謝謝
您需要為heapNode
對象提供比較操作。
a)定義operator<
作為heapNode的成員
struct heapNode
{
int i, j;
double deltaQ;
bool operator<(const heapNode& theOther) const {
// your comparison operation
return this->deltaQ < theOther.deltaQ;
}
};
b)您可以將functor對象作為比較器傳遞給priority_queue構造函數
explicit priority_queue(value_compare const & = value_compare());
定義函子
struct cmp {
bool operator () (const heapNode& lhs, const heapNode& rhs) const {
return lhs.deltaQ < rhs.deltaQ;
}
};
將其傳遞給priority_queue的ctor
cmp c;
boost::heap::priority_queue<heapNode,boost::heap::compare<cmp>> maxHeap{c};
在您的heapNode結構中,您需要重載operator < 。
struct HeapNode
{
int i, j;
double deltaQ;
bool operator<(const HeapNode& other)
{
*return true if current HeapNode is less than other, else false*
};
} heapNode;
http://en.cppreference.com/w/cpp/language/operators將是您的入門指南。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.