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?
views:
535answers:
2
+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
2009-03-14 07:52:06
I forgot about remove_if() +1.
X-Istence
2009-03-14 07:54:24
Very cool. Never seen that before. +1
Bernard
2009-03-14 07:55:18
Thanks, that did the trick.
Ernst Hot
2009-03-14 08:49:43
Well, we don't really need erase; we use because remove variations don't erase the elements, just appends them to the end.
2009-03-16 13:38:11
+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
2009-03-14 08:01:32
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
2009-03-14 08:07:23
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
2009-03-14 12:11:53
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
2009-03-22 08:42:41