I have difficulty understanding how the following function works. I know that it removes an item from an array.
void remove(float a[], int& n, int i){
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
}
I have difficulty understanding how the following function works. I know that it removes an item from an array.
void remove(float a[], int& n, int i){
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
}
This bit of code here is shifting all elements down by 1, essentially overwriting the element at index i
, which is what gets “removed”.
For instance, for an array [10,20,30,40,50]
, if you call the function as remove(arr, 5, 2)
, the first iteration begins with j=i+1
, so j
is index 3
, and the statement a[2] = a[3]
causes the element at index 2
to be overwritten with the element at index 3
, so 30
gets replaced with 40
. In the next (and final) iteration, 40
gets replaced with 50
.
This operation is commonly referred to as “shifting elements” and is common for array manipulation cases where you have to add an element/delete an element, so you have to adjust the remaining elements by “shifting them” up or down, as the case maybe, so you don’t leave “holes” in your array.