Re: exception when using vector
redf0x wrote:
I have contacted a really unreasonable vector exception when I
used its method erase,is there anything wrong int the
following code?
/*sou and dest are both int vector*/
for(vector<int>::iterator bpiter = sou.begin();
bpiter != sou.end();
)
{
if((*bpiter) == 5)
(*bpiter) = 3;
des.push_back(*bpiter);
sou.erase(bpiter);
}
platform VS2005
Yes, your code is faulty. There are very strict rules about what operations
on a vector invalidate which iterators (in fact those rules exist for all
containers). In the case of a vector, erasing an element might mean
reallocation. Further, an iterator is little more than a pointer, which
would have to be adjusted in case of such a reallocation. Now, think
yourself what your erase call does to your iterators and if that isn't an
invalid use.
Further, I don't think you got an exception, at least not in the C++ sense.
You have a stdlib that performs additional checking (which comes at a
cost!) in debug mode to be able to warn you about this invalid use, but
that is not an error that is signalled via exceptions. It is rather an
assertion and the place it occurs should somehow have hinted you to that
fact.
There are several ways to fix this, but in this case I'd simply call
sou.clear() after the loop. Other variants are switching to a list<>, using
a temporary instead of touching the original vector<> to store the final
content and using indices instead of iterators.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]