I'm using for (i = 0; i < array.size(); i++)
is it safe to invoke array.erase()
from within the loop?
It is safe but it is going throw your iteration logic off.
Let's say you have {1 2 3 4 5} in array
.
You removed 2 from the array. At that time, i
is 1. After removing 2, array
is now {1 3 4 5}. You increment i
in the for
statement, which makes i
2. You will end up accessing 4 from the array in the loop, which skips 3 altogether.
In my head I assume for checks array.size()
at every iteration, but maybe it only does it once at initiation.
No, it does that check in every iteration of the loop.
If it did, for (i = 0; i < &array.size(); i++)
would work a fine solution, would it not?
Not sure where you got that idea but it's wrong. Don't even go there.
You can use:
for ( i = 0; i < array.size(); /* Don't increment here */ )
{
// Code
// Check for erase.
if ( check-for-erase-logic )
{
// Erase item
// Don't increment iteration counter.
}
else
{
// Increment iteration counter.
++i;
}
}