As far as the algorithm is concerned, removing a set of element from a contiguous array can be done effectively in two parts.
- Move all the elements not to be deleted to the front of the array.
- Mark the array smaller.
This can be done in C++
with the erase-remove idiom.
vector<T> v; // v = {0,1,2,3,0,0,7};
vector<T>::iterator it = remove(v.begin(),v.end(),e);
// move all elements not to be deleted to the front
// Yes, remove is not the brightest name for that.
// Especially as list::remove really remove elements from the list.
// now v = {1,2,3,7,?,?,?} results marked in question marks
// are implementation dependent.
v.erase(it,v.end());
// get rid of the elements marked as question marks.
// v = {1,2,3,7}
Now, the content of the elements in the question mark is unknown. The only thing we can do with them is get rid of them (by overwriting them, or by removing them).
Is there a real world situation where you need to use remove
without erase? The only situation I could think of is
copy(src.begin(),src.end(),remove(v.begin(),v.end(),e),v.end());
replacing all A
s with B
s, and requiring that all those new B
s will be contiguous. Doesn't make too much sense.
edit: Does it make sense to anything other than contigious memory container (deque
and vector
actually)?
If indeed I'm correct, why was it implemented as a standalone algorithm, instead of vector::remove_if
, dequeue::remove_if
etc.