Mukarram Waqqas
Mukarram Waqqas

Reputation: 95

C++ - Cannot remove the element from the Queue

I'm trying to remove the first element of the Queue but, this does not seem to work. Here is my code:

#include<iostream>
using namespace std;
int front = -1;
int rear = -1;
int i = 0;
const int size = 4;
int Q[size];

bool isEmpty(){
    return front == -1 && rear == -1;
}
bool isFull(){
    return rear == size - 1;
}
void Enqueue(int x){
    if(isFull()){
        cout << "The Queue is full." <<endl;
    }
    else if(isEmpty()){
        front++;
        rear++;
    }
    else{
        rear++;
    }
    Q[rear] = x;
}
void Dequeue(){
    if(isEmpty()){
        cout << "The Queue is empty." << endl;
    }
    else if(front == rear){
        front = -1;
        rear = -1;
    }
    else{
        front++;
    }
}
void display(){
    cout << "The Queue is: " << endl;
    for(i = 0; i <= rear; i++){
        cout << Q[i] << endl;   
    }
}

int main(){
    Enqueue(1);
    Enqueue(2);
    display();
    Dequeue();
    display();
    return 0;
}

This Dequeue() function should remove the element at front but, it is not doing so. This is the output i'm getting from the above code:

The Queue is:
1
2
The Queue is:
1
2

Instead of :

The Queue is:
1
2
The Queue is:
2

I tried some other solutions, but with no luck. I can't seem to wrap my head around it. Any help would be very much appreciated!

Upvotes: 3

Views: 1052

Answers (1)

BeyelerStudios
BeyelerStudios

Reputation: 4283

You forgot to start at front in display. It should look like this instead:

void display(){
    cout << "The Queue is: " << endl;
    for(int i = front; i <= rear; ++i) {
        cout << Q[i] << endl;   
    }
}

Note: This function will behave badly (i.e. produce undefined behaviour) when the queue is empty. You can fix this, by starting with int i = std::max(0, front); or special case the empty case.

Another approach would be to point the rear to the element past the last element. The range front, rear then is empty for front == rear and the number of elements in the range is simply rear - front. This is a common paradigm in C++, see begin and end of any standard container, e.g. std::vector.

Upvotes: 1

Related Questions