Re: removing elements from vector<int> using <algorithm>
arnuld wrote:
On Wed, 10 Oct 2007 02:38:10 -0700, James Kanze wrote:
I'm not sure what this statement is supposed to do, but it
looks very, very wrong (and may not compile with some
implementations).
Note that the statement has a very different meaning
depending on whether vector<>::iterator is a typedef for a
pointer, or is a class type. Since the code shouldn't
compile if it is a typedef for a pointer, I will assume that
it is a class type,
yes, it is a class because VECTOR is a class and erase is its memebr
function.
which means that you have the equivalent of:
begin.operator++( 0 ).operator=( ivec.erase( begin ) ) ;
I dont' know and don't understand what that
begin.operator++( 0 ).operator
means :-(
while ( begin != end ) {
if ( condition ) {
begin = vec.erase( begin ) ;
} else {
++ begin ;
}
}
}
You either increment, or you use the iterator returned by erase.
OK ,i got it but since we have removed the element, so the ivec.end()
iterator defined previously (before erasing) must invalidate but it does
not whereas insert() invalidates such things . I don't understand the
phenomenon.
Of course, the classical idiom would use remove here:
vec.erase(
remove_if( vec.begin(), vec.end(), condition ), vec.end() ) ;
Aha... that's good :-) but that's new to me. so this member function takes
2 arguments:
ivec.erase( algorithm, end_iterator )
it is mysterious, why it takes end_iterator here. I need to look up the
that ERASE member function in Stroustrup .
template < class ForwardIterator, class Predicate >
ForwardIterator remove_if ( ForwardIterator first,
ForwardIterator last,
Predicate pred )
{
ForwardIterator result = first;
for ( ; first != last; ++first)
if (!pred(*first)) *result++ = *first;
return result;
}
actually remove_if does NOT remove any thing, it just move the matched
items forward to overwrite those are not.
std::vector<int>::iterator pos
= remove_if(ivec..begin(), ivec.end(),
std::bind2nd(std::not2(std::modulus<int>()), 2));
now, pos points to the first item that's not matched
iterator vector::erase (iterator first, iterator last);
ivec.erase(pos, ivec.end());
now it's clear that, vector::erase erases a iterator range