How to print a queue?

I am trying to print the line below. I tried to create a temporary queue and write to it, and then write it back.

But it does not work.

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 turn queue<int> myQueue;

Essentially, I want to print this queue without dropping it ... But I'm stuck here.

+4
source share
1 answer

There is no effective way to do this * . But you can do the following:

  • Make a copy of the queue
  • Iterate over the copy, print the front, and then send it

For instance,

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

* , . std::queue C, , . std::queue C. , .

+5

Source: https://habr.com/ru/post/1530814/


All Articles