remove & remove_if ?

Hi, I have been learning from tutorials from pluralsight, and thought all was going well until I started to read through the STL book and read something I think might contradict the tutorials.

Pluralsight taught that the stl remove_if() worked by moving all the elements that you wanted to be removed to the end of the container. So if i had a container such as
1,2,3,4,5,6,7,8
and wanted to remove 4, It would look like
1,2,3,5,6,7,8,4

But the STL book says the remove function (I understand these are different but I assume they would work pretty much the same, one just basically has an if involved) by overwriting the elements you want to remove, and the "extra elements" will be the same elements which were in that location before, ie
1,2,3,4,5,6,7,8
if wanted to remove 4
1,2,3,5,6,7,8,8

So, do these indeed act differently and both pluralsight and the book correct, or is the pluralsight tutorial wrong. It is the c++ standard library book I am reading, so thought that would be more trustworthy.
I'm no expert, but the reference section of this site does not say that remove_if puts the removed elements at the end of the range.
https://en.cppreference.com/w/cpp/algorithm/remove

Neither "moves removed elements". Both move elements that are kept (if necessary).
The value of the elements at the end of array is unknown.

The only difference between std::remove and std::remove_if is in the condition.

You could write remove with remove_if:
1
2
3
4
5
template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value )
{
  return remove_if( first, last, [&value](auto x){return x == value;} );
}
Last edited on
std::remove() and std::remove_if() both return an iterator to the element that follows the last element not removed. Any elements in the range returned_iter to end() iter are undefined.
Topic archived. No new replies allowed.