I'm building a simple list using a dynamically allocated array in C++. I have a function remove(int item) that should remove all occurrences of item in the list. However, if I make a loop that iterates from 0 to length in the array, I'm worried I will exceed the boundaries of my array because length changes as I delete items:
int List::pop(int index)
{
int retval = data[index];
for (int i = index; i < length; i++)
data[i] = data[i+1];
length--;
return retval;
}
void List::remove(int item)
{
for (int i = 0; i < length; i++) {
if (data[i] == item)
pop(i);
}
So, if I called remove(6) on array[6][4][2][6][1][3][5][6], would C++ update the for loop in remove() with the updated value of length after a pop()? Or would it remain the same value that was originally passed to it when remove() was called?
pop()copies the rest of the values one step at a time even if there are multiple copies of the item. You can easily get a single pass O(N) solution by keeping the index of the "packed" data and copying!= itemelements directly there.