My Words list is not accurate

hi I tried another way to clear the Words list from words that are less than 4 or higher than 8 or not isogram

// Clearing words list from non isogram words
    for(int32 index = 0; index < Words.Num(); index++)
    {
        if(Words[index].Len() < 4 || Words[index].Len() > 8 || !IsIsogram(Words[index])) // remove words that are not between 4 - 8 characters and isogram
        {
            Words.RemoveAt(index);
        }
    }

but it’s not clearing properly and I have 652 words left that are included words higher than 8 less than 4 and not isogram.

what am I doing wrong here?

oh I got it I am removing from the Words list and size of it changes.

Generally speaking removing elements whilst iterating the container isn’t a great idea.

Say you have a TArray<int32> and you want to remove odd numbers

TArray<int32> TestData{ 1, 2, 3, 3, 4 };

And you have the following code

for (int32 i = 0; i < TestData.Num(); ++i)
{
    if (TestData[i] % 2 != 0) // if odd
    {
        TestData.RemoveAt(i);
    }
}

Then the loop is going to go

1, 2, 3, 3, 4
^ start, i == 0

1 % 2 == 1 so that will be removed, the elements will be shuffled down and now your array is

2, 3, 3, 4
^ previously 1, i == 0

The loop reaches the end and i is incremented

2, 3, 3, 4
   ^ now here, i == 1

3 % 2 == 1 again, so that is also removed and the elements get shuffled again

2, 3, 4
   ^ 3 removed, i == 1

Then i gets incremented

2, 3, 4
      ^ i == 2

So with that loop 2 was skipped though luckily didn’t need to be removed and so was 3 but it did need to be removed.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms