Search code examples
c++stlerase-remove-idiom

STL "erase-remove" idiom: Why not "resize-remove"?


It is commonly understood that a good way to fully delete desired items from a std::vector is the erase-remove idiom.

As noted in the above link (as of the date of this posting), in code the erase-remove idiom looks like this:

int main()
{
  // initialises a vector that holds the numbers from 0-9.
  std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  // erase-remove idiom to completely eliminate the desired items from the vector
  v.erase( std::remove( std::begin(v), std::end(v), 5 ), std::end(v) ); 
}

I would like to know whether a resize-remove idiom is equivalent in terms of functionality and performance to the erase-remove idiom. Or, perhaps I am missing something obvious?

Is the following resize-remove idiom equivalent to the above erase-remove idiom?

int main()
{
  std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  // Is this "resize-remove" approach equivalent to the "erase-remove" idiom?
  v.resize( std::remove( std::begin(v), std::end(v), 5 ) - v.begin() ); 
}

Solution

  • In my opinion, there are two reasons:

    1. std::remove algorithm requires only Forward Iterator, but - op requires Random Access Iterator.

    2. The result of std::remove means "the new end of container". Logically, we should erase [ "the new end of container" , "the old end of container" ).