1919
2020#include < stdint.h>
2121#include < stdbool.h>
22+ #include < exception>
2223
2324/* *
2425 * Stack has three properties. capacity stands for the maximum number of
@@ -29,9 +30,29 @@ template<typename T=uintptr_t>
2930class Stack
3031{
3132private:
33+ class StackEmptyException : public std ::exception
34+ {
35+ public:
36+ virtual const char * what () const throw()
37+ {
38+ return " stack is empty" ;
39+ }
40+ };
41+
42+ class StackIndexOutOfBoundException : public std ::exception
43+ {
44+ public:
45+ virtual const char * what () const throw()
46+ {
47+ return " Index out of bound." ;
48+ }
49+ };
50+
3251uint32_t m_capacity;// the total capacity
3352uint32_t m_size;// current stack size
3453T * m_elements;// the elements
54+ const StackEmptyException exp_empty;
55+ const StackIndexOutOfBoundException exp_ioob;
3556
3657public:
3758/* *
@@ -47,10 +68,12 @@ class Stack
4768delete [] m_elements;
4869}
4970
71+
5072private:
5173Stack (const Stack&);
5274Stack& operator =(const Stack&);
5375
76+
5477public:
5578/* *
5679 * test whether the stack is empty
@@ -66,9 +89,12 @@ class Stack
6689}
6790
6891/* *
69- * get the top element, test is_empty() before top()
92+ * get the top element
7093*/
71- inline const T& top () const { return m_elements[m_size-1 ]; };
94+ inline const T& top () const {
95+ if (m_size==0 ) throw exp_empty;
96+ return m_elements[m_size-1 ];
97+ };
7298
7399/* *
74100 * push an element into the stack
@@ -88,7 +114,13 @@ class Stack
88114 */
89115inline uint32_t count () const { return m_size; }
90116
91- inline const T& operator [] (int idx) const { return m_elements[m_size-1 -idx]; }
117+ /* *
118+ * return value by index
119+ */
120+ inline const T& operator [] (int idx) const {
121+ if (idx<0 || idx >= m_capacity) throw exp_ioob;
122+ return m_elements[m_size-1 -idx];
123+ }
92124};
93125
94126#endif //
0 commit comments