Home >Backend Development >C++ >How to Safely Remove Items from a Generic List During Iteration?
Avoiding Errors When Removing Items from a List During Iteration:
Modifying a list while iterating through it often leads to the "Collection was modified; enumeration operation may not execute" error. This happens because removing an item invalidates the iterator. Here's how to safely remove elements:
Method 1: Reverse Iteration
Iterating backward prevents index issues when removing items. This approach works well for simple removal criteria.
<code class="language-csharp">for (int i = safePendingList.Count - 1; i >= 0; i--) { // Check removal condition if (shouldRemove) { safePendingList.RemoveAt(i); } }</code>
Method 2: RemoveAll
Method
For more complex removal logic, the RemoveAll
method provides a cleaner solution. It takes a predicate (a function that returns true if an item should be removed) and efficiently removes all matching elements.
<code class="language-csharp">safePendingList.RemoveAll(item => item.Value == someValue);</code>
Summary:
These methods allow for safe and efficient removal of elements from a list during iteration, eliminating the risk of runtime exceptions. Choose the method best suited to your removal criteria and coding style.
The above is the detailed content of How to Safely Remove Items from a Generic List During Iteration?. For more information, please follow other related articles on the PHP Chinese website!