Advertisement
avr39ripe

PV913StaticStackTemplate

Jul 8th, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <typename ElemT, int sizeP>
  4. class Stack
  5. {
  6.     ElemT storage[sizeP];
  7.     int topPosition;
  8.     static const int emptyStack{ -1 };
  9. public:
  10.     Stack() : topPosition{ emptyStack } {};
  11.     int size() const { return sizeP; };
  12.     bool empty() const { return topPosition == emptyStack; };
  13.     bool full() const { return topPosition == sizeP - 1; };
  14.     const ElemT& top() const { return storage[topPosition]; };
  15.     bool topS(ElemT& val)
  16.     {
  17.         if (!empty())
  18.         {
  19.             val = storage[topPosition];
  20.             return true;
  21.         }
  22.         return false;
  23.     };
  24.     bool push(const ElemT& elem)
  25.     {
  26.         if (!full())
  27.         {
  28.             storage[++topPosition] = elem;
  29.             return true;
  30.         }
  31.         return false;
  32.     }
  33.     bool pop()
  34.     {
  35.         if (!empty())
  36.         {
  37.             --topPosition;
  38.             return true;
  39.         }
  40.         return false;
  41.     }
  42.  
  43.     template <typename ElementType, int size>
  44.     friend std::ostream& operator<<(std::ostream&, const Stack<ElementType, size>& stack);
  45. };
  46.  
  47. template <typename ElementType, int size>
  48. std::ostream& operator<<(std::ostream& out, const Stack<ElementType, size>& stack)
  49. {
  50.     if (!stack.empty())
  51.     {
  52.         out << stack.top() << '\n';
  53.     }
  54.     else
  55.     {
  56.         out << "[empty]\n";
  57.     }
  58.     return out;
  59. };
  60.  
  61.  
  62. int main()
  63. {
  64.     Stack<int, 5> stack;
  65.     Stack<char, 8> stackCh;
  66.     std::cout << stack << stackCh;
  67.  
  68.     std::cout << "Pushing in...\n";
  69.     for (int cnt{ 0 }; !stack.full(); stack.push(cnt++))
  70.     {
  71.         std::cout << cnt << '\n';
  72.     }
  73.     stack.push(100);
  74.     std::cout << stack;
  75.  
  76.     std::cout << "Popping out...\n";
  77.     while (!stack.empty())
  78.     {
  79.         std::cout << stack;
  80.         stack.pop();
  81.     }
  82.     stack.pop();
  83.     std::cout << stack;
  84.  
  85.     std::cout << "Pushing in...\n";
  86.     for (int cnt{ 0 }; !stack.full(); stack.push(cnt++))
  87.     {
  88.         std::cout << cnt << '\n';
  89.     }
  90.  
  91.     std::cout << "Popping out...\n";
  92.     while (!stack.empty())
  93.     {
  94.         auto& elem{ stack.top() };
  95.  
  96.         std::cout << elem << ' ';
  97.         stack.pop();
  98.     }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement