I need to iterate over std::queue
.
www.cplusplus.com says:
By default, if no container class is specified for a particular queue class, the standard container class template deque is used.
So can I somehow get to the queue's underlying deque and iterate over it?
Why not just make a copy of the queue that you want to iterate over, and remove items one at a time, printing them as you go? If you want to do more with the elements as you iterate, then a queue is the wrong data structure.
If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?
1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...
if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container
2.The definition of a queue is a FIFO and by definition a FIFO is not iterable
If you need to iterate over a
queue
then you need something more than a queue. The point of the standard container adapters is to provide a minimal interface. If you need to do iteration as well, why not just use a deque (or list) instead?I use something like this. Not very sophisticated but should work.
It will work because when you pop something from q1, and push it into tem, it becomes the first element of tem. So, in the end tem becomes a replica of q1.
you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:
At the end, the tmp_q will be empty but the original queue is untouched.
While I agree with others that direct use of an iterable container is a preferred solution, I want to point out that the C++ standard guarantees enough support for a do-it-yourself solution in case you want it for whatever reason.
Namely, you can inherit from
std::queue
and use its protected memberContainer c;
to access begin() and end() of the underlying container (provided that such methods exist there). Here is an example that works in VS 2010 and tested with ideone: