Does std::stack expose iterators?

Solution 1:

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.

Solution 2:

If you need a stack with iterators, you have two choices:

  • std::vector using push_back(), pop_back().

  • std::deque with either push_back()/pop_back() or push_front()/pop_front().

Solution 3:

The std::stack does expose its underlying container (and therefore iterators) to subclasses through its protected interface. The std::stack's underlying container object corresponds to the (protected) data member c. So if you want to access them, you could extend std::stack a little.

template<typename T, typename Container = std::deque<T>>
class iterable_stack
: public std::stack<T, Container>
{
    using std::stack<T, Container>::c;

public:

    // expose just the iterators of the underlying container
    auto begin() { return std::begin(c); }
    auto end() { return std::end(c); }

    auto begin() const { return std::begin(c); }
    auto end() const { return std::end(c); }
};

int main()
{
    iterable_stack<int> st;

    st.push(2);
    st.push(5);
    st.push(3);
    st.push(7);
    st.push(9);

    for(auto i: st)
        std::cout << i << ' ';
    std::cout << '\n';
}

Output:

2 5 3 7 9 

Solution 4:

In SGI, MSDN and GNU documentations, stack doesn't provide an iterator.