基于vector的栈实现(C++)
write by 九天雁翎(JTianLing) -- blog.csdn.net/vagrxie
头文件:
1 #ifndef __STACK_H__
2 #define __STACK_H__
3 #include <iostream>
4 #include <vector>
5 using namespace std;
6
7 template<typename T>
8 class CStack
9 {
10 public:
11 CStack() { }
12 ~CStack() { }
13
14 size_t empty()
15 {
16 return miDataVec.empty();
17 }
18
19 size_t size()
20 {
21 return miDataVec.size();
22 }
23
24 void pop()
25 {
26 miDataVec.pop_back();
27 }
28
29 T& top()
30 {
31 return miDataVec.back();
32 }
33
34 const T& top() const
35 {
36 return miDataVec.back();
37 }
38
39 void push(const T& aItem)
40 {
41 miDataVec.push_back(aItem);
42 }
43 private:
44 vector<T> miDataVec;
45
46 };
47
48
49
50
51
52
53 #endif
54
测试程序:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <iostream>
4 #include "stack.h"
5 using namespace std;
6
7
8 int main(int argc, char* argv[])
9 {
10 CStack<int> loStack;
11
12 loStack.push(1);
13 cout <<loStack.top() <<" ";
14
15 loStack.push(2);
16 cout <<loStack.top() <<" ";
17
18 loStack.push(1);
19 cout <<loStack.top() <<" ";
20
21 loStack.push(2);
22 cout <<loStack.top() <<" ";
23
24 loStack.push(3);
25 cout <<loStack.top() <<" ";
26
27 loStack.push(4);
28 cout <<loStack.top() <<" ";
29
30 cout <<endl;
31
32 while(loStack.size() != 0)
33 {
34 cout <<loStack.top() <<" ";
35 loStack.pop();
36 }
37
38 cout <<endl;
39
40 exit(0);
41 }
42
这里顺面说明一下,这个实现仅仅是为了说明问题。
在C++中标准的stack实现是通过adaptor设计模式来实现的,并将用于实现的容器放入了模板的参数,以方便你用vector和list,来替代默认的deque。