What is really the difference between the algorithms remove and remove_if and the member function erase? Does both of them result in a call to the removed objects destructor?
A:
Destructor will be always called when removing an item, no matter what method/function you use.
adf88
2010-06-13 10:51:53
I did not upvote, but the downvote is probably due to the fact that neither `std::remove` nor `std::remove_if` algorithms do actually *remove* anything from containers. They only reorder the unwanted elements to the end of the sequence and return an iterator so that it is easy to actually *remove* those elements calling the `erase` method of the specific container
David Rodríguez - dribeas
2010-06-13 11:24:13
+3
A:
No, remove
and remove_if
only move objects around in the sequence. You need to call erase to make the sequence actually shorter. The return value of remove and remove_if is the iterator you can use in an erase
call to shorten the sequence:
sequence.erase(remove(...),sequence.end());
sellibitze
2010-06-13 10:53:45
Yes,but what about the list versions(list.remove/list.remove_if) of the remove and remove_if algorithms?
Eric
2010-06-13 11:10:35
@Eric, you should rephrase your question. Remove and remove_if *algorigthms* are the free functions `remove` and `remove_if` implemented in `<algorithms>`, while `list::remove` and `list::remove_if` are member methods.
David Rodríguez - dribeas
2010-06-13 11:18:51
+3
A:
No, std::remove_if
will move the elements that don't match the predicate to the end of list and will return an iterator to the new "end". Erase will effectively drop the element (call the dtor) from the container.
The difference is perfectly illustrated by the examples here and here.
pmr
2010-06-13 10:54:38
`remove` and `remove_if` do not need to move the "removed" items to the end of the list. The only guarantee is that those items between begin and the returned, new, end are the items that passed the test. After that could be anything. (See Meyer's Effective STL for an example.)
AFoglia
2010-06-16 18:36:17