如何迭代 boost::mutable_queue
我需要一个优先级队列,可以在其中增加或减少优先级键。因此,尽管缺乏文档,boost::mutable_queue 看起来还是很完美。
问题是我需要在某个时刻迭代队列中的所有元素。我怎样才能做到这一点?
或者是否有其他可以工作的数据结构(最好是在 boost 中)?
I need a priority queue where I can increase or decrease the priority key. So boost::mutable_queue seemed perfect despite the lack of documentation.
The problem is that I need to iterate at some point over all the elements in the queue. How can I do that?
Or is there an othe data structure that would work (preferably in boost)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
队列不是为了迭代。队列的全部要点是您只能查看队列前面的元素。
如果您想迭代,那么我建议只使用有序的
std::set
。当您想要修改某个元素时,您必须将其删除并使用新密钥重新插入。您可以使用 mySet.begin() 获取最高优先级元素(它返回一个迭代器)。理想情况下,您需要使用堆。 STL 提供了创建堆的函数,这就是
std::priority_queue
使用的功能。但是,您无法修改堆中的键,因为没有相应的接口。如果您自己管理堆,那么就可以。但是,您需要使用
中的std::__adjust_heap
函数,该函数未记录。您可以在对 Alexander Stepanov 的采访(发明人)中阅读有关此函数为何未记录的所有信息STL)。它必须被“删除”,因为显然 STL 太大了,这也是原始标准中的哈希映射所发生的情况。Queues are not for iteration. The whole point of a queue is that you can only ever look at the element at the front of the queue.
If you want to iterate then I suggest just using an
std::set
, which is ordered. When you want to modify an element, you'll have to remove it and reinsert it with the new key. You can get the highest priority element usingmySet.begin()
(that returns an iterator to it).Ideally, you'll want to use a heap. STL provides functions for making heaps, and that's what the
std::priority_queue
uses. However, you can't modify keys in the heap because there is no interface for it.If you manage the heap yourself then you can. However, you'll need to make use of the
std::__adjust_heap
function from<heap.h>
, which is undocumented. You can read all about why this function is undocumented in this interview with Alexander Stepanov (inventor of the STL). It had to be "removed" because apparently the STL was too big, which is also what happened to hash maps from the original standard.mutable_queue
只是一个适配器。传入适当的底层容器。进一步注意,作为适配器,它会修改您可用的接口。根据定义,队列通常不允许迭代。如果是的话,就不需要这个适配器了。请参阅有关此限制的 SGI STL 文档。您可能需要使用不同的数据结构来实现您的目的。适当的选择取决于您想要如何存储和访问数据。您可能想看一下
std::deque
容器。但是,您需要将优先级编码为所包含对象状态的一部分。The
mutable_queue
is just an adaptor. Pass in an appropriate underlying container. Further note that being an adaptor it modifies the interface that is available to you. By definition, queues typically do not allow iteration. If it did, there'd be no need to have this adaptor. See the SGI STL documentation on this restriction.You possibly need to use a different data structure for your purposes. An appropriate choice depends on how you want to store and access your data. You may want to take a look at the
std::deque
container. However, you will need to encode the priority as part of the contained objects' state.