在 boost::heap::p riority_queue 中推送结构对象时出错

Errors when pushing structure object in boost::heap::priority_queue

本文关键字:结构 出错 对象 queue heap boost riority      更新时间:2023-10-16

我有一个结构,其对象将被推入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')|

任何解决方案,我都是 usinf 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( 您可以将函子对象作为比较器传递给构造函数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 结构中,你需要重载运算符<</em>。

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 对您来说是一个很好的入门指南。