vector<>.erase(where) vs vector<>.erase(from, to)

eric wrote in
news:48f5f7bc$0$5038$e4fe514c@dreader26.news.xs4all.nl:

> Hi all,
>
> Suppose we have a vector of integers:
> vector v;
> filled with some values but not the integer 0 (zero).
>
> Next, we try to remove the zero from the vector:
> vector::iterator it = remove(v.begin(), v.end(), 0);
> Of course, the returned iterator equals v.end().
>
> Now comes the rub: when we erase the element using the iterator
> range version
> v.erase(it, v.end());
> all is fine.
>
> But when we use the single iterator version (for example,
> because I already know that there is only one zero in the
> vector):
> v.erase(it);
> Bad Things Happen: Windows/Visual C++ removes the last element
> of the vector and Linux/g++ segfaults.

You are contradicting yourself. First you say that the vector does
not contain any zeros, then you say that you "already know that
there is only one zero". Both can't be true at the same time.

>
> This means that the remove-erase idiom can't be used in this
> case:
> v.erase(remove(v.begin(), v.end(), 0));
> will give undefined behaviour.

The erase-remove idiom uses the iterator range version of erase:

v.erase( remove( v.begin(), v.end(), 0 ), v.end() );

MV


--
I do not want replies; please follow-up to the group.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google