MyStack(学习)
MyStack.h
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #ifndef _MYSTACK_H
2 #define _MYSTACK_H
3
4 #include "MyUtil.h"
5
6 template<class T>
7 class MyStack
8 {
9
10 public:
11 MyStack(int stackCapacity=10);//默认值是10
12 ~MyStack();
13
14 bool IsEmpty() const;
15 T& Top() const;
16 void Push(const T& item);
17 void Pop();
18 private:
19 T *stack;
20 int top;
21 int capacity;
22
23 };
24
25 template <class T>
26 inline bool MyStack<T>::IsEmpty() const
27 {
28
29 return top == -1;
30 }
31
32 template<class T>
33 inline T& MyStack<T>::Top() const
34 {
35
36 if(IsEmpty()) throw "Stack is empty";
37 return stack[top];//数组---指针 数组---指针 只是写法不一样
38
39 }
40
41 template<class T>
42 void MyStack<T>::Pop()
43 {
44
45 if(IsEmpty()) throw "Stack is empty";
46 else stack[top--].~T();
47
48 }
49
50
51 template <class T>
52 MyStack<T>::MyStack(int stackCapacity):capacity(stackCapacity)//初始化参数
53 {
54
55 if(capacity < 1) throw "stack capacity must be >0 ";
56 stack = new T[capacity];
57 top = -1;
58 }
59
60 template<class T>
61 MyStack<T>::~MyStack()
62 {
63
64 delete[] stack;
65 }
66
67 template<class T>
68 void MyStack<T>::Push(const T& item)
69 {
70 if(top == capacity-1)
71 {
72 ChangeSize1D(stack,capacity,2*capacity);
73 capacity *=2;
74 }
75 stack[++top] = item;
76 }
77
78
79
80 #endif
MyUtil.h
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #ifndef _MYUTIL_H
2 #define _MYUTIL_H
3
4
5 template <class T>
6 void ChangeSize1D(T* &a, const int oldSize,const int newSize)
7 {
8 if(newSize < 0) throw "New length must be >= 0";
9
10 T* temp = new T[newSize];//用new动态创建一个新的数组temp
11 int number = min(oldSize,newSize);
12
13 std::copy(a,a+number,temp);//把a到a+number中的数据都copy到temp数组中
14 delete[] a;
15 a=temp;
16 }
17
18 #endif
main.cpp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//用来测试
#include<iostream>
#include"MyUtil.h"
#include"MyStack.h"
using namespace std;
int main()
{
MyStack<int> st(200);
st.Push(99);
st.Push(22);
st.Push(48);
st.Push(67);
st.Push(100);
st.Pop();
cout << st.Top() << endl;
cout << "测试!"<< endl;
return 0;
}