the erase function

I am trying to write an erase function for a sequence of elements. I understand what is needed to get done. Erase the position requested and all other repetitions of that number in the sequence. I have this, which is incorrect I already know. Now, I do know that whichever element is erased, the sequence then needs to be readjusted so there are no empty slots in the sequence. I have a variable, which is available to these functions, that keeps track of how many elements are in the array, so I need to decrement (elementNumber--). I know what the following function is doing, I just can't find a working solution.


void Sequence::erase( size_type position, size_type count )
{
if( position >= 0 && position + count < numElts )
{
elts[ position ] = 0;
numElts--;
}
else
{
throw exception("Invalid Sequence Index");
}

}

Thanks,

ntox101
After you erase an elements, all the elements that are placed left side of the erased element must be shifted right.

you could right shift elements in following manner,
1
2
3
4
for (int i = position; i < NumElts; i++)
{
   elts[i] = elts[i + 1];
}


before right shift, store the element that you're erasing since you need to erase the other occurrences of that element.

Then start searching the array from the beginning(if the array is not sorted). And right shift the elements each time you find an occurrence.

Last edited on
Topic archived. No new replies allowed.