Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template<class T>
- class Queue
- {
- int head;
- int tail;
- T * array;
- void copyQueue(const Queue<T>& other)
- {
- head = other.head;
- tail = other.tail;
- array = new T[tail - head + 1];
- for(int i = other.head; i <= other.tail; i++)
- array[i] = other.array[i];
- }
- void removeQueue()
- {
- if(array != nullptr)
- delete[] array;
- }
- public:
- Queue<T>() //default constructor
- {
- head = 0;
- tail = -1;
- }
- Queue<T>(const Queue<T>& other) //copy constructor
- {
- copyQueue(other);
- }
- Queue<T>& operator=(const Queue<T>& other) //copy assignment operator
- {
- if(this != &other)
- {
- removeQueue();
- copyQueue(other);
- }
- return *this;
- }
- ~Queue<T>() //destructor
- {
- removeQueue();
- }
- bool isEmpty() const
- {
- return head > tail;
- }
- int size() const
- {
- return tail - head + 1;
- }
- T front() const
- {
- return array[head];
- }
- T back() const
- {
- return array[tail];
- }
- void pop()
- {
- for (int i = head; i <= tail; i++)
- {
- array[i-1] = array[i];
- }
- }
- void push(T element)
- {
- array[++tail] = element;
- }
- void swap(int first, int second)
- {
- if(first!=second && first>=0 && second>=0)
- {
- T temp = array[first];
- array[first] = array[second];
- array[second] = temp;
- }
- }
- void swapQueue(Queue<T>& other)
- {
- Queue temp = *this;
- *this = other;
- other = temp;
- temp.removeQueue();
- }
- friend ostream& operator<<(ostream& os, const Queue<T>& q)
- {
- if(!q.isEmpty())
- {
- os << "Front position: " << q.head << "\nEnd position: " << q.tail << endl;
- for(int i = q.head; i <= q.tail; i++)
- os << q.array[i] << " ";
- os << endl;
- }
- else os << "Empty queue!";
- return os;
- }
- friend istream& operator>>(istream& is, Queue<T>& q)
- {
- is >> q.head >> q.tail;
- for(int i = q.head; i <= q.tail; i++)
- is >> q.array[i];
- return is;
- }
- };
- int main()
- {
- Queue<int> q1;
- cin >> q1;
- cout << q1;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement