6

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?

4 Answers 4

11

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());
2
  • Yes,but what about the list versions(list.remove/list.remove_if) of the remove and remove_if algorithms?
    – Eric
    Jun 13, 2010 at 11:10
  • @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. Jun 13, 2010 at 11:18
9

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.

1
  • 2
    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
    Jun 16, 2010 at 18:36
-2

Destructor will be always called when removing an item, no matter what method/function you use.

1
  • 4
    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 Jun 13, 2010 at 11:24
-3

Quite simply std::remove uses a value to determine if an element is to be "removed" whilst std::remove_if uses a predicate function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.