我需要在我的项目中使用Fibonacci堆,我试图从boost库中使用它。但我无法弄清楚如何为任意数据类型设置用户定义的比较函数。我需要为struct node构造一个min heap,如下所示:
struct node
{
int id;
int weight;
struct node* next;
/* dist is a global array of integers */
bool operator > (struct node b) //Boost generates a Max-heap. What I need is a min-heap.
{return dist[id] < dist[b.id] ? 1:0 ;} //That's why "<" is used for "operator >".
bool operator < (struct node b)
{return dist[id] > dist[b.id] ? 1:0 ;}
bool operator >=(struct node b)
{return dist[id] <= dist[b.id] ? 1:0 ;}
bool operator <=(struct node b)
{return dist[id] >= dist[b.id] ? 1:0 ;}
node()
{
id=0;
weight=0;
next=NULL;
}
};
我查阅了文档并且有一个比较课程。但它不包含任何元素。请告诉我如何设置用户定义的比较功能。 提前谢谢。
答案 0 :(得分:8)
fibonacci_heap
采用比较仿函数,实际上是struct
或class
,带有函数调用运算符 - operator()
。我将简化你的node
结构,但你应该可以稍作修改使用它:
struct node
{
int id;
node(int i)
: id(i)
{ }
};
现在,我们需要定义一个比较node
的类。这将有一个operator()
,它通过const引用获取2个节点,并返回bool
:
struct compare_node
{
bool operator()(const node& n1, const node& n2) const
{
return n1.id > n2.id;
}
};
然后我们可以按如下方式声明我们的堆:
boost::heap::fibonacci_heap<node, boost::heap::compare<compare_node>> heap;
一个完整的例子:
#include <boost/heap/fibonacci_heap.hpp>
#include <iostream>
struct node
{
int id;
node(int i)
: id(i)
{ }
};
struct compare_node
{
bool operator()(const node& n1, const node& n2) const
{
return n1.id > n2.id;
}
};
int main()
{
boost::heap::fibonacci_heap<node, boost::heap::compare<compare_node>> heap;
heap.push(node(3));
heap.push(node(2));
heap.push(node(1));
for(const node& n : heap) {
std::cout << n.id << "\n";
}
}