0

I have a question.

I created a random queue called queue<char> random; and pushed random values into it. I then passed the queue to a function called display_queue and displayed the queue by popping each element out of the queue. However now none of the elements remain in the queue.

Question: Is there a way so that after I display the elements in the queue using the function, it does not change the queue that was passed to it?

By the way I am using the STL queue.

NinjaZ
  • 25
  • 7
  • I presume you're passing your queue to `display_queue` by reference. Don't do that if what you really want is a copy. :P – cHao Nov 15 '14 at 02:07
  • The short answer would be: don't use a queue. You could use (for one example) a `std::deque` instead. It supports all the queue operations, but also supports non-destructive iteration. – Jerry Coffin Nov 15 '14 at 02:07
  • The purpose of the queue is to put items in at one end and pull them out at the other end. Don't use a queue. – xxbbcc Nov 15 '14 at 02:09
  • I need to use a queue for the project, and I was hoping there was a way to do it without using a copy. Like maybe using `Const` somehow? – NinjaZ Nov 15 '14 at 02:09
  • use const reference to avoid copy, and use queue::iterator instead of pop to display so that you would not change the queue passed in – yangguang1029 Nov 15 '14 at 02:16
  • If you *have* to use a queue here, and you *have* to iterate via pop, then a copy is what you want. Then you can modify the copy to your heart's content without breaking the original. `const` would keep you from changing anything, which would keep you from getting the next item. – cHao Nov 15 '14 at 02:16
  • @yangguang1029: Do queues have iterators? – cHao Nov 15 '14 at 02:20
  • Ok so I take it that there is no way other than making a copy then? – NinjaZ Nov 15 '14 at 02:20
  • Sure there is. Use the right container for the job. :P But if you *need* a std::queue, then copy it. Not sure why you're so scared of copies, though -- codewise, it's just deleting a `&`. – cHao Nov 15 '14 at 02:24
  • yeah definetly need to use a queue, the project is done, I ended up using a copy, but was just curious if I could do it a different way. – NinjaZ Nov 15 '14 at 02:25
  • This questoin feels like a duplicate of http://stackoverflow.com/questions/1259099/stl-queue-iteration. – Scott Mitchell Nov 15 '14 at 02:34

0 Answers0