Vladimir Khlghatyan
Vladimir Khlghatyan

Reputation: 11

How to make a C++ STACK container iterable?

Can we write a myStack class that will be implemented in terms of std::stack so that it offers all of its member functions plus an additional feature: iterators?

I tried some options, but they seem to me not quite optimal.

Upvotes: 1

Views: 275

Answers (1)

Daniel Brandão
Daniel Brandão

Reputation: 39

I will show you the way I did it.

stacks are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container

from: https://cplusplus.com/reference/stack/stack/

The stack "underlying container" is deque by default, but can be a vector or a list as well. It's important to know this to answer your question because we are going to use the iterator of the underlying container to make MyStack iterable.

this is the template for the stack class defined in stl_stack.h:

template<typename _Tp, typename _Sequence = deque<_Tp> >
class stack {...}

and this is how I implemented MyStack:

#include <stack>

template<typename T, typename Container = std::deque<T> >
class MyStack : public std::stack<T, Container>
{
    public:
        MyStack(void) : std::stack<T, Container>() {}
        ~MyStack(void) {}

        typedef typename Container::iterator iterator;

        iterator    begin(void) {
            return (this->c.begin());
        }

        iterator    end(void) {
            return (this->c.end());
        }
};

now you can see that this->c is the encapsulated object of the underlying container, so you can use it to access the container methods and add more functionalities to your stack

Upvotes: 0

Related Questions