在 boost::heap::priority_queue 中推送结构对象时出错
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) 你可以将仿函数对象作为比较器传递给 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 将是一个很好的入门指南。
我有一个结构,其对象将被推入 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) 你可以将仿函数对象作为比较器传递给 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
的 ctorcmp 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 将是一个很好的入门指南。