|
| 1 | +// |
| 2 | +// Created by 10578 on 2021/4/6. |
| 3 | +// |
| 4 | + |
| 5 | +#ifndef __CODE_LIBRARY_STACK1_H__ |
| 6 | +#define __CODE_LIBRARY_STACK1_H__ |
| 7 | + |
| 8 | +#include "vector" |
| 9 | +#include "cassert" |
| 10 | +#include "iostream" |
| 11 | + |
| 12 | +template<typename T, template<typename...> class C> |
| 13 | +class Stack; |
| 14 | + |
| 15 | +template<typename T, template<typename...> class C> |
| 16 | +std::ostream &operator<<(std::ostream &os, Stack<T, C> const &s); |
| 17 | + |
| 18 | +template<typename T, template<typename...> class C> |
| 19 | +class Stack { |
| 20 | +private: |
| 21 | + C<T> elems; |
| 22 | + |
| 23 | +public: |
| 24 | + void push(T const &elem); |
| 25 | + T pop(); |
| 26 | + T const & top() const; |
| 27 | + bool empty() const{ |
| 28 | + return elems.empty(); |
| 29 | + } |
| 30 | + |
| 31 | + friend std::ostream& operator<< <T>(std::ostream &os, Stack<T, C> const &s); |
| 32 | +}; |
| 33 | + |
| 34 | +template<typename T, template<typename...> class C> |
| 35 | +void Stack<T, C>::push(T const &elem) { |
| 36 | + elems.push_back(elem); |
| 37 | +} |
| 38 | + |
| 39 | +template<typename T, template<typename...> class C> |
| 40 | +T Stack<T, C>::pop() { |
| 41 | + assert(!elems.empty()); |
| 42 | + T temp = top(); |
| 43 | + elems.pop_back(); |
| 44 | + return temp; |
| 45 | +} |
| 46 | + |
| 47 | +template<typename T, template<typename...> class C> |
| 48 | +T const & Stack<T, C>::top() const { |
| 49 | + assert(!elems.empty()); |
| 50 | + return elems.back(); |
| 51 | +} |
| 52 | + |
| 53 | +template<typename T, template<typename...> class C> |
| 54 | +std::ostream &operator<<(std::ostream &os, Stack<T, C> const &s) { |
| 55 | + for (auto &&x: s.elems) { |
| 56 | + os << x << " "; |
| 57 | + } |
| 58 | + os << std::endl; |
| 59 | + |
| 60 | + return os; |
| 61 | +} |
| 62 | + |
| 63 | +#endif //__CODE_LIBRARY_STACK1_H__ |
0 commit comments