MCPcopy Create free account
hub / github.com/EricPengShuai/Interview / SeqStack

Class SeqStack

base_code/template.cpp:36–119  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

34/* 顺序栈模板 */
35template<typename T>
36class SeqStack
37{
38public:
39 // 构造和析构函数名不用加 <T>,其它出现模板的地方都加上类型参数列表
40 SeqStack(int size = 10)
41 : _pstack(new T[size])
42 , _top(0)
43 , _size(size)
44 {}
45
46 ~SeqStack() {
47 delete []_pstack;
48 _pstack = nullptr;
49 }
50
51 SeqStack(const SeqStack<T> &stack)
52 : _top(stack._top)
53 , _size(stack._size)
54 {
55 _pstack = new T[_size];
56 for (int i = 0; i < _top; ++ i) {
57 _pstack[i] = stack._pstack[i];
58 }
59 }
60
61 SeqStack<T>& operator=(const SeqStack<T> &stack)
62 {
63 if (this == &stack) return *this;
64
65 delete []_pstack;
66
67 _top = stack._top;
68 _size = stack._size;
69 _pstack = new T[_size];
70 // 不用使用 memcpy 进行浅拷贝
71 for (int i = 0; i < _top; ++ i)
72 {
73 _pstack[i] = stack._pstack[i];
74 }
75 return *this;
76 }
77
78 void push(const T &val) // 入栈操作
79 {
80 if (full()) expand();
81 _pstack[_top++] = val;
82 }
83
84 void pop()
85 {
86 if (empty()) return;
87 --_top;
88 }
89
90 T top() const
91 {
92 if (empty()) {
93 throw "stack is empty!"; // 抛异常也代表函数逻辑结束

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected