0

Please help me understand the following code

I know that the following code removes an item from an array. Please let me know how it works. void remove(float a[], int& n, int i){ for (int j=i+1; j<n; j++) a[j-1] = a[j]; --n; }

7th Dec 2019, 5:18 PM
Jack
1 Respuesta
+ 3
Jack Posting full code could help us understand better. Anyways I can just assume what each variable will mean. float a[] - this is array from which you have to remove elements. int &n - This is reference to variable that indicates size of array, number of elements in array. Reference means it's alias for original variable, change in this will be reflected in original one. int i - this is index of element to be removed. 0 1 2 3 4 | ind 10 20 30 40 50 | val Consider this array. Indexing start at 0. Suppose you want to remove element at index 2 so i=2 size, n =5 j=2+1=3 Now the for loop moves (actually copies) all elements 1 index back. a[2] =a[3] a[3]=a[4] At this position loop stops because j<n i.e 5<5 is false. Now you can see new array is. 10 20 40 50 50 Thus index 2 element is removed (overwritten) but now you need to decrease size of array. Which isn't actually possible but you just simulate this by decrementing (--n) size of variable n that indicate size of array.
7th Dec 2019, 5:42 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar