How to traverse stack in C++?

user1857492 picture user1857492 · Apr 21, 2014 · Viewed 30.9k times · Source

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

Traversing using following method is not applicable. Because std::stack has no member end.

std::stack<int> foo;

// ..

for (__typeof(foo.begin()) it = foo.begin(); it != foo.end();  it++)
{
    // ...
}

Answer

utnapistim picture utnapistim · Apr 21, 2014

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.