how to print a stack?

how to print value in a stack?
the following code doesnt work.
http://ideone.com/8u2Fv0
Do you know how your compiler allocates the variables on stack?
by push and pop
So you know, just pop from the stack and print it.

Hint: in the link referred replace the arr[] with arr.pop();
Last edited on
i dont wanna pop it. i need the elements in latter part of recursion. i just wanna print all the elements in the stack at each recursive call.
Stack is special container for which you need to pop the top elements to access the elements below it, unless any special stack constainer gives that access.

What is the stack container you are using, if you are using STL stack, the only way to read the elemetns below is to pop the top.

Hint: You can have a second stack and pop from the first stack, print it, and push it in to seconds stack, then repeat this on all the elements in first stack. When done do the reverse, pop from second stack and push into first stack. this way you will have the fist stack intact
the stack just doesn't allow this

but you can use vector in place of a stack

http://www.cplusplus.com/reference/vector/vector/

instead of push(), pop(), top() you use then push_back(), pop_back(), back()
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <stack>

template < typename T > void print( const std::stack<T>& stk )
{
    struct cheat : std::stack<T> { using std::stack<T>::c ; } ;
    const auto& seq = static_cast< const cheat& >(stk).c ;

    for( const auto& v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}
Topic archived. No new replies allowed.