9.4) Algorithm Examples: Removing A Given Value
To remove the first occurrence of 0 in a container of numbers, we can use the find
algorithm to get an iterator pointing to the value, then use the container's erase
method:
list<int> data; ... list<int>::iterator i = find(data.begin(), data.end(), 0); if (i != data.end()) { data.erase(); }
To remove all occurrences of 0 in a container of numbers, we can use the confusingly-named remove
algorithm to rearrange it so that those occurrences are at the end, then the container's erase
method to actually remove them:
list<int> data; ... list<int>::iterator i = remove(data.begin(), data.end(), 0); data.erase(i, data.end());