Why is it not safe to modify sequence being iterated on?

前端 未结 3 618
孤城傲影
孤城傲影 2020-11-30 12:35

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 12:53

    This is a common problem in many languages. If you have a linear data structure, and you are iterating over it, something must keep track of where you are in the structure. It might be a current index, or a pointer, but it's some kind of finger pointing to the "current place".

    If you modify the list while the iteration is happening, that cursor will likely be incorrect.

    A common problem is that you remove the item under the cursor, everything slides down one, the next iteration of the loop increments the cursor, and you've inadvertently skipped an item.

    Some data structure implementations offer the ability to delete items while iterating, but most do not.

提交回复
热议问题