Does Std::Stack Expose Iterators

Does std::stack expose iterators?

Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).
Stack doc is here.

P.S. According to a comment i got from Iraimbilanja, std::stack by default uses std::deque for implementation.

Why are STL's iterators exposing their container's internals? Why are iterator's member variables mostly public?

Why are STL's iterators exposing their container's internals?

They don't.

Why doesn't the standard require the iterators' internals to be private?

Because that would be of no gain. The standard does not specify that the members are publicly accessible and that should be enough to know that you shall not write code that assumes the members are publicly accessible.

If you are working with an implementation where those members are public and you do access them then you are relying on implementation details and your code is not portable.

Should I expose iterators and adaptor methods or a whole container in C++?

You only expose iterators or iterator-ranges (and typedefed iterator types) unless you absolutely need to expose the container.

This avoids breaking other code when changing the implementation details and also follows the guide-lines of information hiding / encapsulation.

How to traverse stack in C++?

Is it possible to traverse std::stack in C++?

No. A stack is a data structure you should use when you are interested in placing elements on top and getting elements from the top. If you want an iterable stack, either use a different data structure for a stack role (std::vector?) or write one yourself.

How can I expose iterators without exposing the container used?

You may find the following article interesting as it addresses exactly the problem you have posted: On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It

using stack and iterator with auto before initializing causing seg fault

Top doesn't return an iterator, but the top element, although the stack is empty, which causes the error. Stack does not support iterators. It is not a fully-fledged container, but a container adapter, which is like a special typedef for an underlying container, the default of which is deque.

Be aware that certain operations, which depend on the data structure, may invalidate existing iterators. What do you intend to do with your iterator?



Related Topics



Leave a reply



Submit