迭代和修改c++优先级队列

Iterate and modify c++ priority queue

本文关键字:优先级 队列 c++ 修改 迭代      更新时间:2023-10-16

我想要一个可以迭代和修改的优先级队列。也就是说,非常量迭代器。

似乎std::priority_queue<T>不支持修改键值以保护结构的损坏。

我发现boost::heap::prioity_queue支持键的可变性,priority_queue/用update函数修改值以保持数据结构的不变性。

boost也支持迭代器,但它们是常量迭代器,不允许修改。

该标准具有帮助维护堆、make_heappush_heappop_heap的函数。将它们与std::vector或其他随机访问容器结合使用,维护一个可以迭代的堆并不需要太多的工作。

的例子:

std::vector<int> heap = {1,3,5,7,9};
std::make_heap(heap.begin(), heap.end());
// add an element
heap.push_back(4);
std::push_heap(heap.begin(), heap.end());
// remove an element
std::pop_heap(heap.begin(), heap.end());
heap.pop_back();
// multiply each element by 2
for (auto & i : heap)
    i *= 2;

演示

还要注意,所有堆函数都有一个比较器的可选参数,以便您可以控制堆的排序。