模板实现一个栈(内部使用动态申请的数组作为存储结构)

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 template <typename T>
 8 class Stack
 9 {
10 public:
11     Stack(){}
12     ~Stack(){}
13     bool empty()const;
14     void push(T value);
15     T top()const;
16     void pop();
17     int size()const;
18     void printStack()const;
19 private:
20     vector<T> ve;
21 };
22 
23 template <typename T>
24 bool Stack<T>::empty()const
25 {
26     return ve.empty();
27 }
28 
29 template <typename T>
30 void Stack<T>::push(T value)
31 {
32     ve.push_back(value);
33 }
34 
35 template <typename T>
36 T Stack<T>::top()const
37 {
38     return ve.back();
39 }
40 
41 template <typename T>
42 void Stack<T>::pop()
43 {
44     ve.pop_back();
45 }
46 
47 template <typename T>
48 int Stack<T>::size()const
49 {
50     return ve.size();
51 }
52 
53 template <typename T>
54 void Stack<T>::printStack()const
55 {
56     for (auto t : ve)
57         cout << t << " ";
58     cout << endl;
59 }
60 
61 int main()
62 {
63     Stack<int> stk;
64     for (int i = 0; i < 10; i++)
65         stk.push(i);
66     stk.pop();
67     stk.printStack();
68 
69     Stack<string> stringStack;
70     stringStack.push("Chicago");
71     stringStack.push("Denver");
72     stringStack.push("London");
73     stringStack.push("California");
74 
75     cout << stringStack.top() << endl;
76     cout << stringStack.size() << endl;
77     stringStack.printStack();
78     return 0;
79 }

 

posted on 2018-03-22 19:00  lina2014  阅读(151)  评论(0编辑  收藏  举报

导航