Advertisement
vkichukova

Untitled

Oct 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<class T>
  6. class Queue
  7. {
  8. int head;
  9. int tail;
  10. T * array;
  11. void copyQueue(const Queue<T>& other)
  12. {
  13. head = other.head;
  14. tail = other.tail;
  15. array = new T[tail - head + 1];
  16. for(int i = other.head; i <= other.tail; i++)
  17. array[i] = other.array[i];
  18. }
  19. void removeQueue()
  20. {
  21. if(array != nullptr)
  22. delete[] array;
  23. }
  24. public:
  25. Queue<T>() //default constructor
  26. {
  27. head = 0;
  28. tail = -1;
  29. }
  30. Queue<T>(const Queue<T>& other) //copy constructor
  31. {
  32. copyQueue(other);
  33. }
  34. Queue<T>& operator=(const Queue<T>& other) //copy assignment operator
  35. {
  36. if(this != &other)
  37. {
  38. removeQueue();
  39. copyQueue(other);
  40. }
  41. return *this;
  42. }
  43. ~Queue<T>() //destructor
  44. {
  45. removeQueue();
  46. }
  47. bool isEmpty() const
  48. {
  49. return head > tail;
  50. }
  51. int size() const
  52. {
  53. return tail - head + 1;
  54. }
  55. T front() const
  56. {
  57. return array[head];
  58. }
  59. T back() const
  60. {
  61. return array[tail];
  62. }
  63. void pop()
  64. {
  65. for (int i = head; i <= tail; i++)
  66. {
  67. array[i-1] = array[i];
  68. }
  69. }
  70. void push(T element)
  71. {
  72. array[++tail] = element;
  73. }
  74. void swap(int first, int second)
  75. {
  76. if(first!=second && first>=0 && second>=0)
  77. {
  78. T temp = array[first];
  79. array[first] = array[second];
  80. array[second] = temp;
  81. }
  82. }
  83. void swapQueue(Queue<T>& other)
  84. {
  85. Queue temp = *this;
  86. *this = other;
  87. other = temp;
  88. temp.removeQueue();
  89. }
  90. friend ostream& operator<<(ostream& os, const Queue<T>& q)
  91. {
  92. if(!q.isEmpty())
  93. {
  94. os << "Front position: " << q.head << "\nEnd position: " << q.tail << endl;
  95. for(int i = q.head; i <= q.tail; i++)
  96. os << q.array[i] << " ";
  97. os << endl;
  98. }
  99. else os << "Empty queue!";
  100. return os;
  101. }
  102. friend istream& operator>>(istream& is, Queue<T>& q)
  103. {
  104. is >> q.head >> q.tail;
  105. for(int i = q.head; i <= q.tail; i++)
  106. is >> q.array[i];
  107. return is;
  108. }
  109. };
  110.  
  111. int main()
  112. {
  113. Queue<int> q1;
  114. cin >> q1;
  115. cout << q1;
  116. return 0;
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement