gpt4 book ai didi

c++ - 如何打印队列?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:12 27 4
gpt4 key购买 nike

我正在尝试打印 queue以下。我试过创建一个临时 queue 的想法并写入其中然后写回。

但它不起作用。

或者我在这里缺少什么?

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());
}

我的队列是 queue<int> myQueue;

本质上,我想打印这个 queue没有清空它。但我被困在这里。

最佳答案

没有有效的方法可以做到这一点*。但您可以执行以下操作:

  1. 复制队列。
  2. 遍历拷贝,打印正面,然后将其弹出。

例如:

#include <queue>
#include <iostream>

void print_queue(std::queue<int> 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);
}

* 有一个使用继承的 hack。 std::queue 有一个 protected 成员 C,它是保存数据的底层容器。您可以从 std::queue 继承并添加使用 C 进行打印的方法。但是您必须充分意识到从不一定为此设计的类型继承的含义。

关于c++ - 如何打印队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22280318/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com