Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i print a queue?

Tags:

c++

stl

queue

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;

Essentially i want to print this queue without emptying it... But i am stuck here.

like image 354
tyrone 251 Avatar asked Mar 09 '14 09:03

tyrone 251


1 Answers

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

  1. Make a copy of the queue.
  2. Iterate over the copy, printing the front, then popping it.

For example:

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

* 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.

like image 127
juanchopanza Avatar answered Sep 28 '22 00:09

juanchopanza