avr39ripe

cppStaticQueueClass

Aug 3rd, 2021
719
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 Queue
  5. {
  6.     ElemT storage[size];
  7.     int backPosition;
  8.     static const int emptyQueue{ -1 };
  9. public:
  10.     Queue() : backPosition{ emptyQueue } {}
  11.     size_t getSize()const { return size; }
  12.     bool empty()const { return backPosition == emptyQueue; }
  13.     bool full()const { return backPosition == size - 1; }
  14.     ElemT& front() { return storage[0]; }
  15.     const ElemT& front()const { return storage[0]; }
  16.  
  17.     bool push(const ElemT& elem)
  18.     {
  19.         if (!full())
  20.         {
  21.             storage[++backPosition] = elem;
  22.             return true;
  23.         }
  24.         return false;
  25.     }
  26.  
  27.     bool pop()
  28.     {
  29.         if (!empty())
  30.         {
  31.             for (size_t i{ 1 }; i <= backPosition; storage[i - 1] = storage[i], ++i);
  32.             --backPosition;
  33.  
  34.             return true;
  35.         }
  36.         return false;
  37.     }
  38.  
  39.     template <typename ElemT, size_t size>
  40.     friend std::ostream& operator<<(std::ostream& out, const Queue<ElemT, size>& queue);
  41. };
  42.  
  43.  
  44. template <typename ElemT, size_t size>
  45. std::ostream& operator<<(std::ostream& out, const Queue<ElemT, size>& queue)
  46. {
  47.     if (!queue.empty())
  48.     {
  49.         out << "[ ";
  50.         for (size_t i{ 0 }; i <= queue.backPosition; ++i)
  51.         {
  52.             out << queue.storage[i] << ' ';
  53.         }
  54.         out << " ]\n";
  55.     }
  56.     else
  57.     {
  58.         out << "[empty]\n";
  59.     }
  60.     return out;
  61. }
  62.  
  63. int main()
  64. {
  65.     Queue<int, 8> queue;
  66.     std::cout << queue;
  67.  
  68.     std::cout << "Enqueue...\n";
  69.     for (size_t i{ 0 }; !queue.full(); ++i)
  70.     {
  71.         queue.push(i);
  72.         std::cout << i << '\n';
  73.     }
  74.  
  75.     std::cout << "Dequeue...\n";
  76.     for (; !queue.empty(); queue.pop())
  77.     {
  78.         std::cout << queue.front() << '\n';
  79.     }
  80.     queue.pop();
  81.     std::cout << queue;
  82. }
RAW Paste Data