An std:: stack cannot be traversed directly since it lacks an end member, which is how a stack data-structure is supposed to be, with only one pointer.
However, here are two quick ways to get around it:
1) Loop Based:
while(!st.empty()) {
cout << st.top();
st.pop();
}
Problems with the loop-based approach:
- The original stack gets empty.
2) Recursion Based:
template <typename T>
void traverse_stack(stack<T> & st) {
if(st.empty())
return;
T x = st.top();
cout << x << " ";
st.pop();
traverse_stack(st);
st.push(x);
}