如何在boost c++中操作优先级队列中的元素

how to manipulate elements in the priority queue in boost C++

本文关键字:优先级 队列 元素 操作 boost c++      更新时间:2023-10-16

我在处理boost c++中的配对优先级队列时有一个问题。我有一个项目数组{0,1,2,3,…},每个项都有一个优先级值。这些优先级队列构造另一个数组{key0代表项目0,key1代表项目1,…}。

在算法中,我需要选择几个项目将它们放在优先队列中。例如,我可以根据项目1、2、3的优先级值(键)将其选择到队列中。然后,我需要删除一个特定的项目。例如,我可能想从项目1、2、3的队列中删除项目2,并且项目2可能没有最大/最小优先级值。

下面是我使用boost中的配对队列创建的队列。

#include "stdafx.h"
#include <iostream>
#include <boost/heap/pairing_heap.hpp>
pairing_heap<float> pq;
pq.push(1);
pq.push(2.5);
auto handle = pq.push(3.1);
pq.erase(handle); // remove an element by handle
cout << "pq top=" << pq.top() << endl; // a const_reference to the maximum element.

您可以看到,我只能将优先级值推入队列,如果我想要删除一个项目,我需要知道它的句柄值。然而,我不知道如何给处理值大量的项目。希望有人知道怎么做。很多谢谢!

您可以使用s_handle_from_iterator

pq.update(Heap::s_handle_from_iterator(pq.begin()), pq.top()*2);
std::cout << "pq top=" << pq.top() << std::endl;

打印"5"。

这需要一些挖掘,但我发现文档说明操作是恒定时间(文档引用源代码中的d_ary_heap)。

Live On Coliru

#include <boost/heap/pairing_heap.hpp>
#include <iostream>
int main() {
    using Heap = boost::heap::pairing_heap<float>;
    Heap pq;
    pq.push(1);
    pq.push(2.5);
    auto handle = pq.push(3.1);
    pq.erase(handle); // remove an element by handle
    std::cout << "pq top=" << pq.top() << std::endl; // a const_reference to the maximum element.
    pq.update(Heap::s_handle_from_iterator(pq.begin()), pq.top()*2);
    std::cout << "pq top=" << pq.top() << std::endl;
}