c++ - 如何有序遍历 Boost.Heap 优先级队列并更新给定元素?

标签 c++ boost priority-queue

我正在寻找可以保持其元素排序的良好数据结构。目前我正在尝试 Boost.Heap .

我经常需要按顺序遍历数据结构,并在到达基于某些属性的元素时更新其优先级。 Boost.Heap 优先级队列提供有序和无序迭代器。元素更新通过节点句柄发生,句柄可以从普通的无序迭代器中获取,但不能直接从有序迭代器中获取,如下例所示:

#include <iostream>
#include <algorithm>
#include <boost/heap/fibonacci_heap.hpp>

using namespace boost::heap;

int main()
{
    fibonacci_heap<int> fib_heap;

    fib_heap.push(1);
    fib_heap.push(2);
    fib_heap.push(3);

    for(auto i = fib_heap.ordered_begin(); i != fib_heap.ordered_end(); ++i)
    {
        // no viable conversion here
        auto h = fibonacci_heap<int>::s_handle_from_iterator(i);

        if(*h == 2) // dumb test
        {
            fib_heap.increase(h, *h + 2);
            break;
        }
    }

    std::for_each(fib_heap.ordered_begin(), fib_heap.ordered_end(),
    [](const int &e)
    {
        std::cout << e << std::endl;
    });
}

如何有序遍历队列并在遍历中更新一个元素?

请注意,我在更新后留下了遍历。

(欢迎为此目的提出替代库的建议)

最佳答案

如果找不到更好的选择,我需要将句柄保存在每个相应元素内以备后用(c++1y 代码):

#include <iostream>
#include <algorithm>
#include <boost/heap/fibonacci_heap.hpp>

using namespace boost::heap;

template<typename T>
struct heap_data
{
    typedef typename fibonacci_heap<heap_data>::handle_type handle_t;
    handle_t handle;
    T data;

    heap_data(const T &data_) : data(data_) {}

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

void setup_handle(fibonacci_heap<heap_data<int>>::handle_type &&handle)
{
    (*handle).handle = handle;
}

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

    setup_handle(heap.emplace(1));
    setup_handle(heap.emplace(2));
    setup_handle(heap.emplace(3));

    std::find_if(heap.ordered_begin(), heap.ordered_end(),
    [&heap](const heap_data<int> &e)
    {
        if(e.data == 2)
        {
            const_cast<heap_data<int> &>(e).data += 2;
            heap.increase(e.handle);
            return true;
        }
        return false;
    });

    std::for_each(heap.ordered_begin(), heap.ordered_end(),
    [](const heap_data<int> &e)
    {
        std::cout << e.data << std::endl;
    });
}

关于c++ - 如何有序遍历 Boost.Heap 优先级队列并更新给定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102406/

相关文章:

c++ - std::uniform_real_distribution 包含范围

c++ - 使用 boost::thread 发生线程锁。我的条件变量有什么问题?

c++ - 使用 msvc 将 boost 库链接到 qt

c - 具有恒定时间后继操作的优先级队列

c# - 如何高效地重建 FIFO PriorityQueue 内存索引

java - 如何在 Java 中为 PriorityQueue 设置固定大小?

c++ - 在这种情况下, std::stack::push() 和 std::stack::emplace() 之间有区别吗?

c++ - 卸载 DLL 时与时间相关的崩溃?

c++ - 如何在 qmake 项目中使用 Boost 库?

c++ - Boost::Asio 同步客户端超时