c++ - How to copy a stack? -
so utilize dynamic stack , want write re-create constructor, has re-create stack's info instance of same class. i'm trying write function, seems pretty hard. give me hand?
template<typename t=int> class lstack { public: template<typename u=int> struct elem { u con; elem<u>* link; } private: elem<t>* el; void copystack(lstack const& stack) // here { elem<t>* lastly = el; el->con = stack->con; while(stack->link != null) { var temp = new elem<t>; temp->con = stack->con; temp->link = stack->link; stack = stack->link; } } };
the stl container adaptor std::stack
has assignment operator=
allows that
#include <stack> int main() { std::stack<int> s1; std::stack<int> s2; s1 = s2; }
if need manually, can utilize @fredoverflow's recursive solution, or 2 loops , temporary stack, recurisve version keeps on stack frame (pun intended).
void copy_reverse(stack& source, stack& dest) { while(!source.empty()) dest.push(element(source.top())); source.pop(); } } stack src, tmp, dst; copy_reverse(src, tmp); copy_reverse(tmp, dst);
c++
No comments:
Post a Comment