4

所以我使用一个动态堆栈,我想编写一个复制构造函数,它必须从同一个类的另一个实例中复制堆栈的数据。我正在尝试编写该函数,但似乎很难。有人可以帮帮我吗?

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;
        }
    }

};
4

1 回答 1

8

STL 容器适配器std::stack有一个分配operator=,允许您完全做到这一点

#include <stack>

int main()
{
   std::stack<int> s1;
   std::stack<int> s2;
   s1 = s2;
}

如果您需要手动执行此操作,您可以使用@FredOverflow 的递归解决方案,或者您可以使用两个循环和一个临时堆栈来执行此操作,递归版本将其保留在堆栈框架上(双关语)。

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);
于 2013-02-06T19:34:34.850 回答