如何迭代priority_queue?
我可以使用迭代器(如 vector
)在 C++ 中遍历标准 priority_queue
或标准 queue
吗?我不想使用 pop,因为它会导致我的队列出队.
Can I traverse a standard priority_queue
or standard queue
in c++ with an iterator (like a vector
)? I don't want to use pop because it cause my queue to be dequeued.
感谢您的帮助
推荐答案
priority_queue
不允许遍历所有成员,大概是因为太容易使队列的优先级排序无效(通过修改您遍历的元素)或者这可能是不是我的工作"的理由.
priority_queue
doesn't allow iteration through all the members, presumably because it would be too easy in invalidate the priority ordering of the queue (by modifying the elements you traverse) or maybe it's a "not my job" rationale.
官方的解决方法是使用 vector
代替,并使用 make_heap
、push_heap
和 自己管理优先级pop_heap
.在@Richard 的回答中,另一种解决方法是使用从 priority_queue
派生的类,并访问具有 protected
可见性的底层存储.
The official work-around is to use a vector
instead and manage the priority-ness yourself with make_heap
, push_heap
and pop_heap
. Another work-around, in @Richard's answer, is to use a class derived from priority_queue
and access the underlying storage which has protected
visibility.
相关文章