0

I'm learning Data Structures as required of me by my university. I've implemented the Queue DS using Dynamic Array but it somehow doesn't work. It updates the value on the first enqueue method call but from the second call onward, it does nothing.

MY CODE

#include <iostream>
#define MAXSIZE 8

class Queue
{
private:
    int *arr;
    int front;
    int rear;
    int itemsCount;

public:
    Queue()
    {      
        arr = new int[MAXSIZE];
        front = -1;
        rear = -1;
        itemsCount = 0;
    }

    ~Queue()
    {
        delete[] arr;
    }

    int dequeue()
    {

        int x = arr[front];
        front = (front + 1) % MAXSIZE;
        itemsCount--;
        return x;
    }

    void enqueue(int x)
    {
        if (empty())
        {
            front++;
        }

        rear = (rear + 1) % MAXSIZE;
        arr[rear] = x;
        itemsCount++;
    }

    bool full() const
    {
        if (itemsCount == MAXSIZE)
            return true;
        return false;
    }

    bool empty() const
    {
        if (itemsCount == 0)
            return true;
        return false;
    }
};

int main(int argc, char const *argv[])
{
    Queue myQ;

    myQ.enqueue(11);
    myQ.enqueue(22); // This doesn't update the array at 1th index
    myQ.enqueue(33);
    myQ.enqueue(44);
    myQ.enqueue(55);
    myQ.enqueue(66);
    myQ.enqueue(77);
    myQ.enqueue(88);

    std::cout << myQ.dequeue() << std::endl;

    return 0;
}

P.S I know the implementation is incomplete and I haven't handled all the edge cases yet. That's because I couldn't get the normal case to work.

P.P.S It works with Static Array. But not with Dynamically allocated one.

3
  • if (condition) return true; else return false; is better written as return condition;. Commented Dec 13, 2021 at 19:00
  • @KonradRudolph Thank you for replying. I'll take that into consideration. But it doesn't solve the issue I'm facing. Commented Dec 13, 2021 at 19:11
  • … hence I wrote a comment, not an answer. Commented Dec 13, 2021 at 19:15

1 Answer 1

0

Apparently, the array was being updated and the program was running as it should have when I performed the dequeue operations and displayed the values on screen. But the debugger somehow was only showing the value at the first index of the dynamically allocated array.

array pointer

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.