问题描述
我可以使用迭代器遍历标准的 priority_queue
或标准队列
c> vector )?我不想使用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.
感谢任何帮助
推荐答案
A queue
有目的地提供了一个有限的接口,不包括迭代。但由于队列
使用 deque
作为底层容器,为什么不使用 deque
直接?
A queue
purposefully provides a limited interface, which excludes iteration. But since a queue
uses a deque
as the underlying container, why not use a deque
directly?
#include <iostream>
#include <queue>
using namespace std;
int main() {
deque<int> q;
q.push_back(1);
q.push_back(2);
q.push_back(3);
for(deque<int>::iterator it = q.begin(); it != q.end(); ++it)
cout << *it << endl;
}
优先级队列的类似答案:不,你不能。在这种情况下,默认使用向量
。在这两种情况下,您都不能访问底层容器以对其进行迭代。有关详情,请参见。
Similar answer for a priority queue: no, you cannot. In this case though, a vector
is used by default. In neither case can you access the underlying container to iterate over them. See this question for further reading.
这篇关于如何迭代一个priority_queue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!