Is it safe to remove an element from an array during a foreach?

Hi,

I am searching through an array and want to remove items that I have finished with. Is it safe to do a remove index during a foreach?

Thanks in advance

Simon

Hey there, there is a good chance of skipping items. Let’s say you removed item 5, then item 6 would become the new item 5, but your loop would continue from the new item no 6. So one entry would be skipped. You can solve this by storing the indices of items you want to remove in an integer array, the nremoving them once the loop is finished.

In most languages removing items from an array during an iteration (for each) could result in unpredictable behavior. I have not tried this in UE4 blueprints, but I assume it could result in items being skipped. A safer solution would be to store the indices that needs to be removed into an array during for-each and remove those indices from outside the for-each loop. Another option would be to use a flag in your array elements and mark them if you dont want them anymore. But this method is very much dependent on the type of elements you are putting into the array.

If you want to loop through the array and remover multiple items then yes, it could mess you up a little since you’ll be changing what items are at which index. You’ll have to create some additional logic to account for this.

You could use a for loop with break, and then decrement the index each time you remove an item so that you don’t end up skipping items.

The problem with counting forward is that removing an index causes all future indices to shift down by 1.

The traditional way to do this in all programming languages is to iterate through your array in reverse order from MaxElements to 0. If you remove an element when counting in reverse it doesn’t affect the indices of the remaining elements in the array.

1 Like

You can add mid loop(to the end of the array), but removal could be a problem.

In your case what I would do would be to keep the original array and use that for a ForEachLoop. Then, crease a new array that takes all the add/remove updates. Then, when the ForEach is complete, merge your new array back into the old.

This might work as well Reverse for each as than it should not mater if the index is moved around on ones you have already cleared

Use Reversed-foreach loop !! otherwise, it’ll skip some items.

1 Like