C++的Stack模板的簡單實現

Cosmop01itan發表於2017-04-01
template <typename T,int stacksize>
class Stack
{
private:
T elems[stacksize];
int size;
public:
Stack() :size(0)
{

}
void push(T const& e)
{
if (size >= stacksize)
throw out_of_range("Stack<>::push():stack is full");
elems[size] = e;
size++;
}
T pop()
{
if (size <= 0)
{
throw out_of_range("Stack<>:pop():stack is empty");
}
size--;//指到的一直都是最後一個的後一個
return elems[size];
}
bool empty()
{
return size == 0;
}
T top()
{
return elems[size - 1];
}
};
int main(int argc, char *argv[], char *env[])
{

Stack<int, 40> s40stack;
for (int i = 0; i < 20; i++)
s40stack.push(i + 1);

for (int i = 0; i < 20; i++)

cout << s40stack.pop() << ends;


system("pause");
return 0;
}

相關文章