On Mon, 22 Sep 2014 20:18:32 -0700, MikeCopeland <
mrc...@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);
> }
Since you increment vIter even when you do an erase, you will skip
over the next element after each erase. Consider the case where your
vector contains 0,1,2,3,4. If you delete the element when the
iterator points to 2, the vector becomes 0,1,3,4 and your iterator
points to 3. You then increment the iterator for the next iteration
and it points to 4. You never process the element containing 3.
As soon as vIter points past the halfway point of the vector elements,
vIter+iii will point beyond the end of the vector. In the above
example, if 3 is the first element you choose to delete, vIter+iii is
an invalid iterator value (well beyond the end of the vector).
Ian's post shows you how to solve the first problem. Since we don't
know what vIter+iii is supposed to be, it's a little harder to suggest
a solution for the second.
--
Remove del for email