std::vector Iterator Invalidation: Invalidating All Iterators After Erase
It's commonly understood that erasing an element from a vector only invalidates iterators pointing to positions after the erased element. However, a key issue arises: is the iterator at the erased position still valid?
According to the C Standard, the answer is no. All iterators at or after the iterator(s) passed to erase are invalidated. This implies that the following code, which aims to remove odd integers from a vector, will result in undefined behavior:
<code class="cpp">typedef std::vector<int> vectype; vectype vec; // Initialize the vector for (int i = 0; i < 100; ++i) vec.push_back(i); vectype::iterator it = vec.begin(); while (it != vec.end()) { if (*it % 2 == 1) vec.erase(it); // Invalidating iterator else ++it; }</code>
Handling Iteration Correctly
To handle iteration correctly after erasing, use the iterator returned by erase. This iterator points to the element immediately after the erased element(s) (or to the end if there is none).
In this case, a more efficient approach for removing odd integers would be to employ the erase-remove idiom:
<code class="cpp">bool is_odd(int x) { return (x % 2) == 1; } vec.erase(std::remove_if(vec.begin(), vec.end(), is_odd), vec.end());</code>
The above is the detailed content of ## Are All Iterators Invalid After `erase` on a `std::vector`?. For more information, please follow other related articles on the PHP Chinese website!