的std ::队列迭代
-
12-09-2019 - |
题
我需要遍历std::queue
。
www.cplusplus.com表示:
默认情况下,如果用于特定队列类没有指定的容器类,标准容器类模板双端队列被使用。
所以,我可以以某种方式获取到队列的底层双端队列和迭代呢?
解决方案
如果您需要遍历一个queue
那么你需要的东西比一个队列多。标准集装箱适配器的点是提供一种最小接口。如果你需要做的迭代,以及,为什么不直接使用双端队列(或目录)呢?
其他提示
虽然我与其他人同意,直接使用可迭代的容器是首选的解决方案,我想指出的是,C ++标准,保证了足够的支持,做自己动手的情况下,解决方案,您希望它无论出于何种原因。
即,可以从std::queue
继承和使用它的保护构件Container c;
访问begin()和()结尾的底层容器的(前提是这样的方法存在有)。下面是在VS 2010的工作原理的示例,并且与ideone 测试:
#include <queue>
#include <deque>
#include <iostream>
template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
typedef typename Container::iterator iterator;
typedef typename Container::const_iterator const_iterator;
iterator begin() { return this->c.begin(); }
iterator end() { return this->c.end(); }
const_iterator begin() const { return this->c.begin(); }
const_iterator end() const { return this->c.end(); }
};
int main() {
iterable_queue<int> int_queue;
for(int i=0; i<10; ++i)
int_queue.push(i);
for(auto it=int_queue.begin(); it!=int_queue.end();++it)
std::cout << *it << "\n";
return 0;
}
可以将原始队列保存到临时队列。然后,你只需做临时队列您的正常弹出要经过原,例如:
queue tmp_q = original_q; //copy the original queue to the temporary queue
while (!tmp_q.empty())
{
q_element = tmp_q.front();
std::cout << q_element <<"\n";
tmp_q.pop();
}
目前结束时,tmp_q将是空的,但原始队列是不变。
为什么不只是让你想遍历队列的副本,并删除项目之一的时间,打印他们为你去吗?如果要使用的元素做更多的作为你迭代,那么队列是错误的数据结构。
而阿列克谢Kukanov的回答可能更有效,还可以通过在一个很自然的方式队列迭代,通过弹出每个从队列的前部元件,然后将其推到背:
#include <iostream>
#include <queue>
using namespace std;
int main() {
//populate queue
queue<int> q;
for (int i = 0; i < 10; ++i) q.push(i);
// iterate through queue
for (size_t i = 0; i < q.size(); ++i) {
int elem = std::move(q.front());
q.pop();
elem *= elem;
q.push(std::move(elem));
}
//print queue
while (!q.empty()) {
cout << q.front() << ' ';
q.pop();
}
}
输出:
0 1 4 9 16 25 36 49 64 81
如果您需要遍历队列......队列是不是你所需要的容器。点击 你为什么选择一个队列?点击 你为什么不拿一个容器,你可以遍历?
1.如果您选择一个队列,那么你说你想包装容器成“队列”接口: - 面前 - 背部 - 推 - 流行 - ...
如果你也想迭代,队列有一个不正确的接口。队列是提供原始容器的受限子集的适配器
队列的定义2.是一个FIFO,并通过定义一个FIFO不迭代
我用这样的事情。不是很复杂的,但应该工作。
queue<int> tem;
while(!q1.empty()) // q1 is your initial queue.
{
int u = q1.front();
// do what you need to do with this value.
q1.pop();
tem.push(u);
}
while(!tem.empty())
{
int u = tem.front();
tem.pop();
q1.push(u); // putting it back in our original queue.
}
这会工作,因为当你突然从Q1的东西,并将其推入TEM,它成为TEM的第一要素。那么,到底TEM成为Q1的翻版。
在短:无
有一个劈,使用载体作为垫层容器,所以queue::front
会返回有效的引用,将其转换为指针的迭代,直到<= queue::back
std::queue
是容器适配器,并且可以指定所使用的容器(它默认使用deque
)。如果您需要在适配超出了功能,那么只使用一个deque
或直接在另一容器中。