So I use a dynamic stack and I want to write a copy constructor, which has to copy the stack's data from another instance of the same class. I'm trying to write the function, but it seems pretty hard. Could somebody give me a 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>* last = 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 an assignment operator=
that allows you to do exactly that
#include <stack>
int main()
{
std::stack<int> s1;
std::stack<int> s2;
s1 = s2;
}
If you need to do it manually, you can use @FredOverflow's recursive solution, or you could do it with two loops and a temporary Stack, which the recurisve version keeps on the 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With