Re: exception when using vector
redf0x ha scritto:
Hello,everyone:
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);
}
once you do "sou.erase(bpiter)", bpiter becomes an invalid iterator that
can't be used anymore. In particular, you can't compare it with
sou.end(). Why don't you write your code like this:
for(vector<int>::iterator bpiter = sou.begin();
bpiter != sou.end(); ++bpiter)
{
if((*bpiter) == 5)
(*bpiter) = 3;
des.push_back(*bpiter);
}
sou.clear();
In addition to avoid invalidating the iterator, it's much better to
erase all elements in one single call to clear(), rather than one at a
time with erase(). Remember that each time you erase one element from
the front of the vector you have to move *every other element* down one
position.
In this particular case, you can also avoid the loop entirely, as
there's an STL algorithm that performs exactly what you are trying to do:
std::replace_copy(
sou.begin(), sou.end(), std::back_inserter(des), 5, 3);
sou.clear();
In order to increase performances by reducing the need for repeated
allocations, you can add a call to reserve(), as you know that the final
number of elements in des will be des.size() + sou.size().
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]