在boost中定义fibonacci堆的比较函数

cau*_*n14 5 c++ templates boost fibonacci-heap

我需要在我的项目中使用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;
    }

};
Run Code Online (Sandbox Code Playgroud)

我查阅了文档并且有一个比较课程.但它不包含任何元素.请告诉我如何设置用户定义的比较功能.先感谢您.

Yuu*_*shi 8

fibonacci_heap采用比较仿函数,它实际上是一个structclass一个函数调用操作符 - operator().我将简化你的node结构,但你应该可以使用这个稍作修改:

struct node
{
    int id;

    node(int i)
      : id(i)
    { }
};
Run Code Online (Sandbox Code Playgroud)

现在,我们需要定义一个比较nodes 的类.这将operator()通过const引用获取2个节点,并返回bool:

struct compare_node
{
    bool operator()(const node& n1, const node& n2) const
    {
        return n1.id > n2.id;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后我们可以按如下方式声明我们的堆:

boost::heap::fibonacci_heap<node, boost::heap::compare<compare_node>> heap;
Run Code Online (Sandbox Code Playgroud)

一个完整的例子:

#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";
    }
}
Run Code Online (Sandbox Code Playgroud)