+ 2

Please explain me this code mainly that void remove() ...In void remove there is for loop so how it remove only first element wh

#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){ size+=1; queue[size-1]=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.print(); return 0; }

24th Feb 2022, 11:42 AM
Sabnis Ashutosh
Sabnis Ashutosh - avatar
5 Respuestas
+ 3
You're asking what the work of "remove" function is, right? I assume that's what you're asking The "remove" function checks if the queue is empty. If it's empty then it returns after printing "queue is empty". If the queue is not empty, then it loop from the first element to the element before the last element, and swaps every element with its successor. Let me explain this with an example. Consider the queue {1,2,3,4,5} Before remove: 1 -> 2 -> 3 -> 4 -> 5 After remove: 2 -> 3 -> 4 -> 5 Imagine a real life queue, what will you do to remove 1 person from it? You'll make the first person to away, and bring the others front. This function does the same
24th Feb 2022, 12:04 PM
Rishi
Rishi - avatar
+ 3
Sabnis Ashutosh happy to help :D
24th Feb 2022, 1:38 PM
Rishi
Rishi - avatar
+ 2
But it's a for loop so it will remove every element how it's remove only one element if we pass only once the remove in main ???
24th Feb 2022, 12:12 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar
+ 2
Sabnis Ashutosh in my example, it changes 1 to 2, 2 to 3, 3 to 4 and 4 to 5 arr={1,2,3,4,5} Iteration expansion(0 to size-1(not included) meaning 0 to 3: i=0: arr[i]=arr[i+1] arr[0]=arr[1] 1=2 arr={2,2,3,4,5} i=1: arr[i]=arr[i+1] arr[1]=arr[2] 2=3 arr={2,3,3,4,5} i=2: arr[i]=arr[i+1] arr[2]=arr[3] 3=4 arr={2,3,4,4,5} i=3: arr[i]=arr[i+1] arr[3]=arr[4] 4=5 arr={2,3,4,5,5} size-- so now size=4 Finally, arr={2,3,4,5}
24th Feb 2022, 12:57 PM
Rishi
Rishi - avatar
+ 2
Thank you 😊
24th Feb 2022, 1:26 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar