如何使我的堆栈类动态

时间:2011-12-12 13:24:42

标签: c++ dynamic stack

我用c ++编写了一个堆栈类(如下所示),但它是静态的,确定它使用了大量的内存。我怎么能让它变得动态,所以当它需要它时,它会为对象添加一些内存,当我弹出内存时,内存会自动删除?

template <class T>
class stack
{
private:
    T value[512];
    uint16_t length;
public:
    stack()
    {
        length=0;
    }

    stack(T _input)
    {
        value[0]=_input;
        length=1;
    }

    bool push(T _input)
    {
        if(length+1<512)
        {
            value[++length]=_input;
            return true;    
        }
        else
            return false;
    }

    T pop()
    {
        return value[length--];     
    }

    T peak()
    {
        return value[length];   
    }

    bool has_data()
    {
        return (length>0?true:false);
    }

};

3 个答案:

答案 0 :(得分:3)

你也可以使用std :: vector:

template <class T>
class stack{
private:
std::vector<T> vec;
public:
inline void push(T arg){vec.push_back(arg);};
inline T pop(){return vec.pop_back();};
};

答案 1 :(得分:3)

您必须在需要时动态分配它。这样的事情可能是:

#define STACK_INITIAL_ALLOC   32
#define STACK_CHUNK_ALLOC    32

template<typename T>
class Stack
{
public:
    Stack()
        : data(0), entries(0), allocated(0)
        { }

    Stack(const T &value)
        : data(0), entries(0), allocated(0)
        {
            push(input);
        }

    ~Stack()
        {
            if (data)
                delete [] data;
        }

    void push(const T &value)
        {
            if (entries == allocated)
                allocate();  // Allocate more memory

            data[entries++] = value;
        }

    T pop()
        {
            if (entries > 0)
            {
                shrink();
                return data[--entries];
            }
            else
                throw runtime_error("stack empty");
        }

    T &top()
        {
            if (entries > 0)
                return data[entries - 1];
            else
                throw runtime_error("stack empty");
        }

    // Return the number of entries in the stack
    size_t count() const
        {
            return entries;
        }

private:
    T      *data;      // The actual stack
    size_t  entries;   // Number of entries in stack
    size_t  allocated; // Allocated entries in stack

    void copy(T *from, T *to)
        {
            for (size_t i = 0; i < entries; i++)
                *to++ = *from++
        }

    void allocate()
        {
            if (data == 0)
            {
                allocated = STACK_INITIAL_ALLOC;
                data = new T[allocated];
            }
            else
            {
                // We need to allocate more memory

                size_t new_allocated = allocated + STACK_CHUNK_ALLOC;
                T *new_data = new T[new_allocated];

                // Copy from old stack to new stack
                copy(data, new_data);

                // Delete the old data
                delete [] data;

                allocated = new_allocated;
                data = new_data;
            }
        }

    // Shrink the stack, if lots of it is unused
    void shrink()
        {
            // The limit which the number of entries must be lower than
            size_t shrink_limit = allocated - STACK_CHUNK_ALLOC * 2;

            // Do not shrink if we will get lower than the initial allocation (shrink_limit > STACK_INITIAL_ALLOC)
            if (shrink_limit > STACK_INITIAL_ALLOC && entries < shrink_limit)
            {
                // We can shrink the allocated memory a little
                size_t new_allocated = allocated - STACK_CHUNK_ALLOC;

                T *new_data = new T[new_size];

                copy(data, new_data);

                delete [] data;

                data = new_data;
                allocated = new_allocated;
            }
        }
};

同样是一个小免责声明,此代码直接写入浏览器。它没有经过测试,但原则上应该有效......:)

答案 2 :(得分:0)

任何类似结构的数组的增长和缩小都是昂贵的(T必须是可复制构造的)并且必须移动所有现有的T。如果您发现正在进行大量推送/弹出,并且需要保持较低的内存使用率,请尝试在内部使用链接列表。它只需要单独联系。

这是一幅草图:

template <class T>
class stack
{
  struct Node
  {
    T data;
    Node* next;
  };
public:

  // methods

private:
  Node *head;
};

现在,要在堆栈上推送内容,使用Node构建T,将其设置为当前head的下一个指针,将head设置为Node 1}}指针。弹出包括从next获取head并将其设置为head

当然,您需要在销毁等方面正确管理内存。

编辑:啊我认为你可能知道C ++的基础知识是错误的,我假设你在使用模板的时候做了。在这种情况下 - 忽略这个答案,直到你学会了基础知识!