Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between erase and remove/remove_if algorithms?

Tags:

c++

stl

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?

like image 481
Eric Avatar asked Jul 18 '26 03:07

Eric


2 Answers

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());
like image 121
sellibitze Avatar answered Jul 19 '26 17:07

sellibitze


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.

like image 36
pmr Avatar answered Jul 19 '26 16:07

pmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!