I have implemented a queue ADT using circular array. However, I want to be able to copy all content of the circular array to a bigger array when full. I have read about the system.arraycopy in Java, but this function does not exist in C++. In the enqueue function below, if the array is full, instead of throwing an error, it should copy into a bigger array.
My code:
template <class Obj>
class Circular_Queue
{
int MAX;
private:
Obj *cqueue_arr;
Obj *cqueue_arr2;
int front, rear;
public:
Circular_Queue()
{
cqueue_arr = NULL;
cout << "Enter size of the queue:";
cin >> MAX;
cqueue_arr = new Obj[MAX];
rear = -1, front = -1;
}
~Circular_Queue() {
delete[]cqueue_arr;
}
void qfront() {
if (front == -1)
{
throw QueueEmptyException();
}
cout << "Front item is : " << cqueue_arr[front] << endl;
}
//Insert into Circular Queue
void enqueue(Obj item)
{
int i;
if ((front == 0 && rear == MAX - 1) || (front == (rear + 1)% MAX))
{
Obj* cqueue_arr2 = new Obj[MAX * 2]; // Creates a bigger array.
for (int i = 0; i < (MAX * 2); i++) { // This section doesnt workas intended.
cqueue_arr2[i] = cqueue_arr[i];
}
}
if (front == -1)
{
front = 0;
rear = 0;
}
else
{
if (rear == MAX - 1)
rear = 0;
else
rear = ((rear + 1) % MAX);
}
cqueue_arr[rear] = item;
cout << "Insertion Success!!!\n";
cout << "The number of space left in the queue is ";
cout << MAX - (rear + 1) << endl;
cout << " \n";
cout << "Content of new array is:";
for (int i = 0; i < MAX * 2; i++)
cout << cqueue_arr[i] << " ";
}
// Delete from Circular Queue
Obj dequeue()
{
if (front == -1)
{
throw QueueEmptyException();
}
cout << "Element deleted from queue is : " << cqueue_arr[front] << endl;
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
if (front == MAX - 1)
front = 0;
else
front = ((front + 1) % MAX);
}
}
//Display Circular Queue
void display()
{
int front_pos = front, rear_pos = rear;
if (front == -1)
{
cout << "Cannot display, Queue is EMPTY!\n";
return;
}
cout << "Circular Queue elements are:\n";
if (front_pos <= rear_pos)
{
while (front_pos <= rear_pos)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
}
else
{
while (front_pos <= MAX - 1)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
front_pos = 0;
while (front_pos <= rear_pos)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
}
cout << endl;
}
};