Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining compare function for fibonacci heap in boost

I need to use Fibonacci heap in my project and I am trying to use it from boost library. But I cannot figure out how to set up a user defined compare function for arbitrary data type. I need to construct a min heap for struct node defined as follows:

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;
    }

};

I looked up the documentation and there was a compare class. But it did not contain any element. Please tell me how to set up a user defined compare function. Thank you in advance.

like image 925
cauthon14 Avatar asked May 23 '13 04:05

cauthon14


1 Answers

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";
    }
}
like image 60
Yuushi Avatar answered Oct 16 '22 00:10

Yuushi