Answer to Question #294582 in C++ for Roe

Question #294582

Write a c++ program that

Has a class named Queue for storing integers. In a queue, the elements are retrieved in a FIFO fashion.The class contains:


■ An int[] data fieldnamed elements that stores the int values in the queue.


■ A data field named size that stores the number of elements inthe queue.


■ A constructor that createsa Queue object with defaultcapacity 8 .


■ The method enqueue(int v) that adds v into the queue.


■ The method dequeue() that removes and returns theelement from the queue.


■ The method empty() that returns true if the queue isempty.


■ The method getSize() that returns the size of the queue.


Implement the class with the initial arraysize set to 8. The array size will be doubled once the number of the elementsexceeds the size. After an element is removed from the beginning of thearray,you need to shift all elements in the array one position the

left. Writea test program that adds 20 numbers from 1 to 20 into the queue and removesthese numbers and displays them.


1
Expert's answer
2022-02-06T17:17:17-0500
#include <iostream>
using namespace std;


class Queue {
private:
    int* elements;
    int size;
    int current;


public:
    Queue(int capacity=8);
    ~Queue();
    void enquue(int v);
    int dequeue();
    bool empty() { return current == 0; }
    int getSize() { return size; }
};


Queue::Queue(int capacity) : size(capacity), current(0) {
    elements = new int[size];
}


Queue::~Queue() {
    delete [] elements;
}


void Queue::enquue(int v) {
    if (current < size) {
        elements[current++] = v;
    }
}


int Queue::dequeue() {
    if (current == 0) {
        return 0;
    }
    int res = elements[0];


    for (int i=1; i<current; i++) {
        elements[i-1] = elements[i];
    }
    current--;
    return res;
}


int main() {
    Queue q(20); 


    for (int i=1; i<=20; i++) {
        q.enquue(i);
    }


    while (!q.empty()) {
        int v = q.dequeue();
        cout << v << " ";
    }
    cout << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog