Defining compare function for fibonacci heap in boost

江枫思渺然 提交于 2019-12-01 05:51:09

fibonacci_heap takes a comparison functor, which is effectively a struct or class with a function call operator - operator(). I'm going to simplify your node struct, but you should be able to use this with minor modifications:

struct node
{
    int id;

    node(int i)
      : id(i)
    { }
};

Now, we need to define a class that compares nodes. This will have an operator() that takes 2 nodes by const reference, and return a bool:

struct compare_node
{
    bool operator()(const node& n1, const node& n2) const
    {
        return n1.id > n2.id;
    }
};

We can then declare our heap as follows:

boost::heap::fibonacci_heap<node, boost::heap::compare<compare_node>> heap;

A full example:

#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";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!