wohxela
wohxela

Reputation: 35

Deleting an element of an array within a for loop - problem with the for loop skipping the next entry

To continue on from the title, I am deleting an element of an array within a for loop - the problem is the fact that the for loop then goes on to read the next element. Because (for example) array number 20 is deleted, 21 becomes 20 and so in the next loop of the for loop, 20 (previously 21) is now skipped...!

In more detail: I have a for loop, within it I access the corresponding element of array[i], there is a statement in the loop that deletes that entry of the array if it fits a condition (don't worry about what the condition is).

for(i=0;i<total;++i)
{
    // if something is true (don't worry about what), the total reduces by 1.
    // then, in order to 
}

My problem is that when that element of the array is deleted in another for loop, the previous for loop will skip what was once the element after because it is now in the place of the element that has just been covered in the previous for loop.

for (int c = i; c < totaltri; c++)
{
    trilist[c] = trilist[c+1];
}

I know it's rather confusing but I've done my best to explain, I'm hoping that someone has a workaround...!

Upvotes: 0

Views: 43

Answers (1)

4386427
4386427

Reputation: 44368

Is this what you are looking for:

for(i=0;i<total;++i)
{
    if (delete_i'th_element)
    {
        --total;
        for (int c = i; c < total; c++)
        {
            trilist[c] = trilist[c+1];
        }
        --i;  // Decrement i to compensate for the increment in outer loop
    }
    else
    {
        ... other code
    }
}

An alternative approach:

i = 0;
while(i<total)
{
    if (delete_i'th_element)
    {
        --total;
        for (int c = i; c < total; c++)
        {
            trilist[c] = trilist[c+1];
        }
    }
    else
    {
        ... other code

        ++i;  // Increment i when the i'th element is processed
    }
}

Upvotes: 1

Related Questions