On Mon, 22 Sep 2014 20:18:32 -0700
MikeCopeland <mrc2323@cox.net> wrote:
I'm having difficulty deleting items from a vector, and I suspect
it's a problem with how I'm using my iterator.
I my vector populated, and after some logic I wish to scan the
vector and erase certain items as I go. Below is the actual code I
use, and the program aborts when I execute the first "erase" call.
In my application, I can't do the delete "outside" of the loop.
Given the code below, is there a way to delete object from a
vector in this manner...or how might I do it? Please advise. TIA
for(vIter = defVect.begin(), iii = 0; vIter != defVect.end();
vIter++, iii++)
{
defWork = *vIter;
if(defWork.recVal >= uuu)
defVect.erase(vIter+iii);
}
Modifying the size of a vector may invalidate all iterators pointing to
it, so of course your code has a high likelihood of crashing. Furthermore,
even if you rewrote it to use indices rather than iterators and got
the iteration logic right, that code would degrade into quadratic
complexity because a single erase in a vector is already O(N). A much
better approch is to iterate from start to finish and copy all elements
you want to keep so they'll all end up at the start, then after the
iteration truncate the vector to its new size; this is O(N) no matter
how much you erase. So basically (untested)
for (vIter = defVect.begin(), vDest = vIter; vIter != defVect.end(); ++vIter)
{
if (!deletePredicate(*vIter))
{
*vDest = *vIter;
++vDest;
}
}
defVect.erase(vDest, defVect.end());
In either case, I too warmly recommend the "move, then erase" approach.