C++ 如何打印队列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22280318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i print a queue?
提问by tyrone 251
I am trying to print a queue below. I have tried the idea of creating a temp queue and writing into it then writing it back.
我正在尝试在下面打印一个队列。我尝试过创建一个临时队列并写入它然后将其写回的想法。
But its not working.
但它不起作用。
Or what am i missing here?
或者我在这里错过了什么?
for(int i = 1; i<myQueue.size(); i++)
{
queue<int> tempQueue;
cout << myQueue.front() << endl;
MytempQueue.push(myQueue.front());
myQueue.pop();
myQueue.push(myTempQueue.back());
}
My queue is queue<int> myQueue;
我的队列是 queue<int> myQueue;
Essentially i want to print this queue without emptying it... But i am stuck here.
基本上我想打印这个队列而不清空它......但我被困在这里。
回答by juanchopanza
There is no efficient way to do this*. But you can do the following:
没有有效的方法来做到这一点*。但是您可以执行以下操作:
- Make a copy of the queue
- Iterate over the copy, printing the front, then popping it
- 制作队列的副本
- 迭代副本,打印正面,然后弹出
For example,
例如,
#include <queue>
#include <iostream>
void print_queue(std::queue q)
{
while (!q.empty())
{
std::cout << q.front() << " ";
q.pop();
}
std::cout << std::endl;
}
int main()
{
std::queue<int> q;
for (auto i : {1,2,3,7,4,9,7,2,4}) q.push(i);
print_queue(q);
}
* There's a hack using inheritance. std::queue
has a protected member C
which is the underlying container holding the data. You could inherit from std::queue
and add methods to do the printing using C
. But you have to be fully aware of the implications of inheriting from a type that is not necessarily designed for that.
* 有一个使用继承的技巧。std::queue
有一个受保护的成员C
,它是保存数据的底层容器。您可以继承std::queue
并添加方法来使用C
. 但是您必须充分意识到从不一定为此而设计的类型继承的含义。