Advertisement
Neveles

Untitled

Mar 29th, 2020
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <iostream>
  4. #include "Queue.h"
  5.  
  6. template <class T>
  7. class QueueArray : public Queue<T>
  8. {
  9. public:
  10.   QueueArray(int size = 100); // size задает размер "по умолчанию"
  11.   QueueArray(const QueueArray<T>& src);
  12.   virtual ~QueueArray()
  13.   {
  14.     delete[] array_;
  15.   }
  16.   void enQueue(const T& e);
  17.   const T& deQueue();
  18.   bool isEmpty()
  19.   {
  20.     return head_ == tail_;
  21.   }
  22.   void print(std::ostream& out);
  23.  
  24. private:
  25.   T* array_; // массив элементов очереди
  26.   int head_ = 1; // Очередь пуста, если head[Q] = tail[Q].
  27.   int tail_ = 1; // Первоначально: head[Q] = tail[Q] = 1;
  28.   int size_; // размер очереди
  29. };
  30.  
  31. template <class T>
  32. QueueArray<T>::QueueArray(int size)
  33. {
  34.   try
  35.   {
  36.     array_ = new T[size_ = size];
  37.   }
  38.   catch (...)
  39.   {
  40.     throw WrongQueueSize();
  41.   }
  42.   head_ = 1;
  43.   tail_ = 1;
  44. }
  45.  
  46. template <class T>
  47. QueueArray<T>::QueueArray(const QueueArray<T>& src)
  48. {
  49.   try
  50.   {
  51.     array_ = new T[size_ = src.size_];
  52.   }
  53.   catch (...)
  54.   {
  55.     throw WrongQueueSize();
  56.   }
  57.  
  58. }
  59.  
  60. template <class T>
  61. void QueueArray<T>::enQueue(const T& e)
  62. {
  63.   if (head_ == tail_ + 1)
  64.   {
  65.     throw QueueOverflow();
  66.   }
  67.  
  68.   tail_ = (tail_ + 1) % size_;
  69.   array_[tail_] = e;
  70. }
  71.  
  72. template <class T>
  73. const T& QueueArray<T>::deQueue()
  74. {
  75.   if (head_ == tail_)
  76.   {
  77.     throw QueueUnderflow();
  78.   }
  79.  
  80.   T copy = array_[head_];
  81.   head_ = (head_ + 1) % size_;
  82.   return copy;
  83. }
  84.  
  85. template <class T>
  86. void QueueArray<T>::print(std::ostream& out)
  87. {
  88.   if (head_ == tail_)
  89.   {
  90.     return;
  91.   }
  92.   int count;
  93.   int ix;
  94.   for (ix = (head_ % size_) + 1, count = 1; count <= tail_ - 1; ix = (ix + 1) % size_, count++)
  95.   {
  96.     out << array_[ix] << " ";
  97.   }
  98.   out << "\n";
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement