**模拟实现栈**
#include<iostream>
#include<windows.h>
#include<stack>
using namespace std;
template<class T>
class Stack
{
public:
Stack(size_t capacity = 5)
{
_capacity = capacity+3;
_pData = new T[_capacity];
_size = 0;
}
Stack(const Stack<T>& s)
{
T *Ptemp = new T[s._capacity];
for (size_t i = 0; i < s._size; ++i)
{
Ptemp[i] = s._pData[i];
}
delete[]_pData;
_pData = Ptemp;
_capacity = s._capacity;
_size = s._size;
}
Stack<T>& operator=(const Stack<T>& s)
{
if (this == &s)
return *this;
delete[]_pData;
T *pTemp = new T[s._capacity];
for (size_t i = 0; i < s._size; ++i)
{
pTemp[i] = s._pData[i];
}
_pData = pTemp;
_capacity = s._capacity;
_size = s._size;
return *this;
}
void Push(const T& x)
{
_CheckCapacity();
_pData[_size++]=x;
}
void Pop()
{
if (!Empty())
{
_pData[_size--];
}
}
size_t Size()const
{
return _size;
}
T Top()
{
return _pData[_size-1];
}
const T& Top()const
{
return _pData[_size-1];
}
bool Empty()const
{
if (0 == _size)
return true;
return false;
}
void Print()
{
for (size_t i = 0; i<_size; ++i)
{
cout << *(_pData + i) << " " ;
}
cout << endl;
}
private:
void _CheckCapacity()
{
if (_size >= _capacity)
{
T* pTemp = new T[_capacity*2 + 3];
for (size_t i = 0; i < _size; i++)
{
pTemp[i] = _pData[i];
}
delete[]_pData;
_pData = pTemp;
_capacity *= 2;
}
}
private:
T* _pData;
size_t _capacity;
size_t _size;
};
int main()
{
Stack<int>s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
Stack<int>s1(s);
cout << "************* Stack<int>s1(s) ***************" << endl;
s1.Print();
cout << "s1.Size()" << " " << s1.Size() << endl;
cout << "s1.Top()" << " " << s1.Top() << endl;
cout << "s1.Empty()" << " " << s1.Empty() << endl;
cout << "************* Pop()两个元素之后 *************" << endl;
s1.Pop();
s1.Pop();
s1.Print();
cout << "s1.Size()" << " " << s1.Size() << endl;
cout << "s1.Top()" << " " << s1.Top() << endl;
cout << "s1.Empty()" << " " << s1.Empty() << endl;
cout << "************* Stack<int>s2; s2 = s ************" << endl;
Stack<int>s2;
s2 = s;
s2.Print();
cout << "s2.Size()" << " " << s2.Size() << endl;
cout << "s2.Top()" << " " << s2.Top() << endl;
cout << "s2.Empty()" << " " << s2.Empty() << endl;
cout << "************** Pop()三个元素之后 ************" << endl;
s2.Pop();
s2.Pop();
s2.Pop();
s2.Print();
cout << "s2.Size()" << " " << s2.Size() << endl;
cout << "s2.Top()" << " " << s2.Top() << endl;
cout << "s2.Empty()" << " " << s2.Empty() << endl;
system("pause");
return 0;
}
