當需要出現時,您必須動態分配它。事情是這樣的,也許:
#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;
}
}
};
也是一個小聲明,該代碼被寫入直接在瀏覽器中。它沒有經過測試,但應該原則上...... :)
簡單的回答:使用'std :: stack'。 :P真正的答案:獲得[良好的書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)並瞭解'新'和動態內存分配。 – Xeo
我忘了說:當我在微處理器上編寫代碼時,我不能使用標準庫,如std :: stack – mefmef
究竟是什麼原因阻止您使用標準庫? – Xeo