#include<stack>
#include<iostream>
using namespace std;
template<class T>
class Stack
{
public:
Stack()
:_array(0)
,_size(0)
,_capacity(3)
{
_array = new T[_capacity];
}
void Push(const T& data)
{
CheckCapacity();
_array[_size] = data;
_size++;
}
void Pop()
{
_size--;
}
T& Top()
{
return _array[_size - 1];
}
T& Top()const
{
return _array[_size - 1];
}
size_t Size()const
{
return _size;
}
bool Empty()const
{
if (_size)
return false;
else
return true;
}
private:
void CheckCapacity()
{
size_t size = Size();
size_t newcapacity = 2 * _capacity + 2;
if (size == _capacity)
{
T*temp = new T[newcapacity];
_capacity = newcapacity;
for (size_t i = 0; i < size; ++i)
{
temp[i] = _array[i];
}
delete[] _array;
_array = temp;
}
}
T* _array;
size_t _capacity;//容量
size_t _size;//元素个数
};
int main()
{
Stack<int>s;
/*stack<int> s;*/
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
size_t size = s.Size();
cout << size << endl;
s.Pop();
size_t size1 = s.Size();
cout << size1 << endl;
return 0;
}
以下为代码测试结果: