Modify the ArrayQueue class to make the array queue capacity extendable. Assumin
ID: 3829848 • Letter: M
Question
Modify the ArrayQueue class to make the array queue capacity extendable. Assuming the default queue capacity is 5.
You only need to write and show the C++ codes to implement the below two functions:
a. void resize(int N);
This function resizes the current queue array capacity to N.
b. void enqueue(const E& e);
This function appends a new element to the back of the queue. If the queue is full then it calls the resize function to double the current capacity and then en-queue the new element to the new capacity queue.
Example of an Extendable Array Queue Class declaration:
template <typename E>
class ExtArrayQueue {
enum { DEF_CAPACITY = 5 }; // default queue capacity
public:
ExtArrayQueue(int cap = DEF_CAPACITY); // constructor from capacity
int size() const; // number of items in the queue
bool empty() const; // is the queue empty?
const E& front() const; // get the front element
void enqueue(const E& e); // add to back of queue
void dequeue(); // remove from front of queue
void printAll(); // print all elements in the queue
Private:
void resize(int N); // resize the array to size N
E* Q; // array of queue elements
int capacity; // queue capacity
int f; // index of the front of the queue
int r; // index of the rear of the queue
int n; // number of elements
};
Explanation / Answer
template <typename E>
class ExtArrayQueue {
enum { DEF_CAPACITY = 5 }; // default queue capacity
public:
ExtArrayQueue(int cap = DEF_CAPACITY); // constructor from capacity
int size() const; // number of items in the queue
bool empty() const; // is the queue empty?
const E& front() const; // get the front element
void enqueue(const E& e); // add to back of queue
void dequeue(); // remove from front of queue
void printAll(); // print all elements in the queue
Private:
void resize(int N); // resize the array to size N
E* Q; // array of queue elements
int capacity; // queue capacity
int f; // index of the front of the queue
int r; // index of the rear of the queue
int n; // number of elements
};
template <typename E> // This function resizes the current queue array capacity to N
void ArrayQueue<E>::resize(int N) {
if (size() == capacity) throw length_error("enqueue to full queue");
N = N + 5;
maxSize = N;
E * temp = new E[maxSize];
temp = Q;
delete[] Q;
Q = new E[maxSize];
Q = temp;
delete[] temp;
}
template <typename E> // This function appends a new element to the back of the queue. If the
void ArrayQueue<E>::enqueue(const E& e) {
if (size() == capacity) throw length_error("enqueue to full queue");
{
N = n;
resize(int N);
}
Q[r] = e;
r = (r + 1) % capacity;
n++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.