avr39ripe

cppStaticStackClass

Aug 3rd, 2021
578
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. template <typename ElemT, size_t size>
  4. class Stack
  5. {
  6.     ElemT storage[size];
  7.     int topPosition;
  8.     static const int emptyStack{ -1 };
  9. public:
  10.     Stack() : topPosition{ emptyStack } {}
  11.     size_t getSize()const { return size; }
  12.     bool empty()const { return topPosition == emptyStack; }
  13.     bool full()const { return topPosition == size - 1; }
  14.     ElemT& top() { return storage[topPosition]; }
  15.     const ElemT& top()const { return storage[topPosition]; }
  16.     bool push(const ElemT& elem)
  17.     {
  18.         if (!full())
  19.         {
  20.             storage[++topPosition] = elem;
  21.             return true;
  22.         }
  23.         return false;
  24.     }
  25.  
  26.     bool pop()
  27.     {
  28.         if (!empty())
  29.         {
  30.             --topPosition;
  31.             return true;
  32.         }
  33.         return false;
  34.     }
  35.  
  36.     template <typename ElemT, size_t size>
  37.     friend std::ostream& operator<<(std::ostream& out, const Stack<ElemT, size>& stack);
  38. };
  39.  
  40.  
  41. template <typename ElemT, size_t size>
  42. std::ostream& operator<<(std::ostream& out, const Stack<ElemT, size>& stack)
  43. {
  44.     if (!stack.empty())
  45.     {
  46.         out << stack.top() << '\n';
  47.     }
  48.     else
  49.     {
  50.         out << "[empty]\n";
  51.     }
  52.     return out;
  53. }
  54.  
  55. int main()
  56. {
  57.     Stack<int, 5> stack;
  58.  
  59.     std::cout << "Pushing in...\n";
  60.     for (int cnt{ 0 }; !stack.full(); stack.push(cnt++))
  61.     {
  62.         std::cout << cnt << '\n';
  63.     }
  64.     stack.push(100);
  65.     std::cout << stack << '\n';
  66.  
  67.     std::cout << "Poping out...\n";
  68.     for (;!stack.empty(); stack.pop())
  69.     {
  70.         std::cout << stack;
  71.     }
  72.     stack.pop();
  73.     std::cout << stack;
  74.  
  75. }
RAW Paste Data