+ 1

Can anyone explain to me how does this work?

So, after about one day, I finally "guessed" the solution for Queue Management Part 1. However, I still cannot understand how does the code work. Can anyone explain it to me? Thank you very much for your answers. Here is my code: #include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout <<endl; } //your code goes here void add(int x) { queue[size++]=x; } }; int main() { Queue q; q.add(42); q.add(2); q.add(8); q.add(1); q.print(); q.remove(); q.add(128); q.print(); q.remove(); q.remove(); q.pri

7th Feb 2022, 12:55 PM
adeadaccount
1 ответ
+ 1
The code is basically data structure Queue implementation. This code implements Queue using an array where ...... 1. Member function 'add(int x)' is for pushing an element to the last of Queue. 2. Member function 'remove()' is for popping out an element from the front of the array because of which all elements are shifted 1 place leftward and size variable is decremented by 1. 3. Member function 'void print()' is for printing the Queue, basically the array which is used in the implementation of Queue. let's run it.... Queue q; // Queue class object is declared which fires non-arg ctor in your class q.add(42); q.add(2); q.add(8); q.add(1); // push 42 , push 2, push 8, push 1 //Till here we have Queue [42, 2, 8, 1] q.print();// prints Queue [42, 2, 8, 1] q.remove(); // pop out first element i.e. 42 from the Queue // Now we have Queue [2, 8, 1] q.add(128); // push 128 q.print(); // printing Queue [128, 2, 8, 1] q.remove(); // pop 128, now 2 comes to front q.remove(); // pop 2 q.print();// printing Queue [8, 1]
7th Feb 2022, 1:23 PM
saurabh
saurabh - avatar