1

I was trying to iterate over a STL stack in c++ but was unable to do so.

Is it even possible to iterate over a C++ STL Stack or Queue without popping(Like vectors)?

SUMIT
  • 42
  • 8
  • 1
    A stack loses its meaning if you want to just iterate over it and it is not possible. As you suggested, you should use a vector instead of that. – Croppi May 11 '19 at 14:36
  • You can access to the underlying protected member `std::queue::c` using the function proposed by [these answers](https://stackoverflow.com/questions/1185252/is-there-a-way-to-access-the-underlying-container-of-stl-container-adaptors#3). – Hiroki May 11 '19 at 14:43
  • @Hiroki but why use `std::queue` then? – Matteo Italia May 11 '19 at 15:06
  • 1
    @MatteoItalia Yeah, there might be no reason. I completely agree to use `std::deque` :) – Hiroki May 11 '19 at 15:09

1 Answers1

0

No, you cannot iterate over a std::queue since that is not its purpose.

A container that allows fast insertion at both ends, as well as iteration, is std::deque. Note that iteration is slower than for a std::vector, but insertion/removal at the beginning is much faster.

Paul92
  • 8,827
  • 1
  • 23
  • 37
  • Friendly reminder that `std::queue` isn't an actual container, but a container adaptor whose only purpose in life is to dumb down `std::deque` interface. – Matteo Italia May 11 '19 at 14:59
  • @MatteoItalia You're right, thanks a lot for pointing that out. – Paul92 May 11 '19 at 16:12