main.cpp

#include<iostream>

#include<string>

#include"Stack.hpp"

using namespace std;


void test1(){                     //测试

Stack<int> s1;

s1.Push(1);

s1.Push(2);

s1.Push(3);

s1.Push(4);


s1.Pop();

s1.Pop();

s1.Pop();

s1.Pop();

}


int main(){

test1();

return 0;

}

Stack.hpp

#pragma once


template <class T>            //使用模板可以实现多种类型栈操作

class Stack{

private:

T* _array;           //数据结构

size_t _capacity;     //入栈个数

int _topindex;     //栈空/满的判断标准

public:

Stack()

:_array(0)

, _capacity(0)

, _topindex(-1)

{}

void Push(const T& x){           //入栈

if (_topindex + 1 == _capacity){     //判断是否需要开辟空间

_capacity = 2 * _capacity + 3;

T* tmp = new T(_capacity);

if (tmp == NULL){

cout << "failed new" << endl;

exit(-1);

}

memcpy(tmp, _array, sizeof(T)*(_topindex + 1)); //内置类型使用   

delete _array;                                 // memcpy ,自定义

_array = tmp;                                 //使用for循环逐个拷贝

}                                                    //注意深拷贝和前拷贝

_array[++_topindex] = x;

}

void Pop(){                          //出栈

if (_topindex > -1){

cout << _array[_topindex] << endl;

_topindex--;

}

}

bool empty(){           //清空栈

return _topindex = -1;

}

};