[英]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.