1

我试图在我的实现中使用来自 boost 的斐波那契堆,但是我的程序崩溃了,当我调用 reduce 函数时,这个例子(W 是一个简单的类):

struct heap_data
{
    boost::heap::fibonacci_heap<heap_data>::handle_type handle;
    W* payload;

    heap_data(W* w)
    {
        payload = w;
    }

    bool operator<(heap_data const & rhs) const
    {
        return payload->get_key() < rhs.payload->get_key();
    }
};



int main()
{
    boost::heap::fibonacci_heap<heap_data> heap;

    vector<heap_data> A;

    for (int i = 0; i < 10; i++)
    {
        W* w = new W(i, i + 3);
        heap_data f(w);

        A.push_back(f);

        boost::heap::fibonacci_heap<heap_data>::handle_type handle = heap.push(f);
        (*handle).handle = handle; // store handle in node
    }

    A[5].payload->decr();

    heap.decrease(A[5].handle);

    return 0;
}
4

1 回答 1

2

这个问题很琐碎。

你有两个容器(向量A和堆heap)。

堆包含向量中数据的副本:

A.push_back(f);                    // copies f!
handle_type handle = heap.push(f); // copies f again!

您仅在堆中的副本上设置句柄:

(*handle).handle = handle; // store handle in the heap node only

因此,在临时元素f和 vectorA的元素中, 的值handle不确定的(您只是没有给它任何值)。

因此,当你这样做

heap.decrease(A[5].handle);

您调用未定义的行为是因为您依赖于A[5].handle未初始化的值。

更简单,正确的例子:

Live On Coliru

#include <boost/heap/fibonacci_heap.hpp>
#include <boost/tuple/tuple_comparison.hpp>

struct W {
    int a;
    int b;

    W(int a, int b) : a(a), b(b) { }

    boost::tuple<int const&, int const&> get_key() const { return boost::tie(a, b); }

    void decr() { b?a:--a, b?--b:b; }
};

struct heap_data;
using Heap = boost::heap::fibonacci_heap<heap_data>;

struct heap_data
{
    W payload;
    Heap::handle_type handle;

    heap_data(W w) : payload(w), handle() {}

    bool operator<(heap_data const & rhs) const {
        return payload.get_key() < rhs.payload.get_key();
    }
};

#include <vector>
#include <iostream>

int main()
{
    Heap heap;

    std::vector<Heap::handle_type> handles;

    for (int i = 0; i < 10; i++)
    {
        Heap::handle_type h = heap.push(W { i, i + 3 });
        handles.push_back(h);
        (*h).handle = h;
    }

    (*handles[5]).payload.decr();
    heap.decrease(handles[5]);
}
于 2015-05-26T21:48:26.323 回答