remove(), remove_copy()
remove() separates out all instances of a value within the sequence. It does not actually erase the matched elements (the container's size is preserved). Rather, each nonmatching element is assigned in turn to the next free slot. The returned iterator marks 1 past the new range of elements.
For example, consider the sequence {0,1,0,2,0,3,0,4}. Let's say that we wish to remove all 0 values. The resulting sequence is {1,2,3,4,0,3,0,4}. The 1 is copied into the first slot, the 2 into the second slot, the 3 into the third slot, and the 4 into the fourth slot. The 0 at the fifth slot represents the leftover of the algorithm. The returned iterator addresses that slot. Typically, this iterator is then passed to erase(). (The built-in array is not suited to the remove() algorithm because it cannot be resized easily. For this reason, the remove_copy() is the preferred algorithm for use with an array.)
#include <algorithm>
int ia[] = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5 };
vector<int> vec( ia, ia+10 );
// vector after remove, without applying erase():
// 1 2 3 4 5 3 0 4 0 5
vec_iter = remove( vec.begin(), vec.end(), 0 );
// vector after erase(): 1 2 3 4 5
vec.erase( vec_iter, vec.end() );
int ia2[5];
// ia2: 1 2 3 4 5
remove_copy( ia, ia+10, ia2, 0 );
|