views:

535

answers:

2

If for instance you have a std::vector<MyClass>, where MyClass has a public method: bool isTiredOfLife(), how do you remove the elements that return true?

+16  A: 

I prefer remove_if

v.erase(remove_if(v.begin(), v.end(), 
                 mem_fun_ref(&MyClass::isTiredOfLife)), 
        v.end());

remove_if returns an iterator pointing after the last element that's still in the sequence. erase erases everything from its first to its last argument (both iterators).

Johannes Schaub - litb
I forgot about remove_if() +1.
X-Istence
Very cool. Never seen that before. +1
Bernard
Thanks, that did the trick.
Ernst Hot
Well, we don't really need erase; we use because remove variations don't erase the elements, just appends them to the end.
+4  A: 

Using remove_if is the "right" way to do this. Be careful NOT to use an iterator to cycle through and erase, because removing items invalidates the iterator. In fact, any example which uses erase() as its primary method is a bad idea on vectors, because erase is O(n), which will make your algorithm O(n^2). This should be an O(n) algorithm.

I think remove_if is a little complex, but the example given above is good. Here is another good O(n) way to do it:

for( size_t i = 0; i < vec.size(); )
   if( vec[i].isTiredOfLife() )
   {
      vec[i] = vec.back();
      vec.pop_back();
   }
   else
      ++i;
AHelps
D'oh. I forgot about that. It's even in bold in the page I linked. :o I've deleted my post, so no-one uses it.
Bernard
Won't this rearrange the elements in the vector? Assuming that, for example, the input vector is sorted, the output vector won't, the last element will take the position of the first deleted element.
David Rodríguez - dribeas
You might want to update your answer to not refer to Bernard's anymore.
Kristo
Yes, this will rearrange the elements in the vector. That's good if you don't care about order (it's probably faster than remove_if, especially if the datatype is complex), but it's bad if you need relative order to remain the same.
AHelps