Eric
Eric

Reputation: 589

difference between erase and remove/remove_if algorithms?

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?

Upvotes: 7

Views: 7061

Answers (4)

AndyKenZ
AndyKenZ

Reputation: 37

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

Upvotes: -3

pmr
pmr

Reputation: 59811

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.

Upvotes: 10

sellibitze
sellibitze

Reputation: 28097

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());

Upvotes: 11

adf88
adf88

Reputation: 4442

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

Upvotes: -2

Related Questions