This post will discuss how to traverse a stack in C++.

The std::stack container does not have any std::begin or std::end member function, and there isn’t any overload of std::begin which accepts a std::stack. We cannot use it with a range-based for-loop. In other words, std::stack is not meant to be iterated over.

 
Although it is not possible to directly traverse a std::stack, you can create a copy of the original stack and process its items, one at a time, and then remove it with the standard pop function until the stack gets empty. This way the original stack remains untouched, but its copy becomes empty.

Download  Run Code

Output:

4
3
2
1

 
We can also recursively print the contents of the stack and avoid creating a temporary copy of it. This, however, uses an implicit stack (call stack) for recursion and may exhaust heap memory for a very large stack.

Download  Run Code

Output:

4
3
2
1

 
A better alternative is to use std::deque instead, which can be iterated over using the range-based for-loop. A std::deque supports all standard operations of a std::stack. For example, we can insert and remove items from one end of a deque (say front) using the push_front and pop_front functions.

Download  Run Code

Output:

4
3
2
1

That’s all about traversing a stack in C++.