Home > Backend Development > C++ > ## Are All Iterators Invalid After `erase` on a `std::vector`?

## Are All Iterators Invalid After `erase` on a `std::vector`?

Barbara Streisand
Release: 2024-10-25 10:43:30
Original
691 people have browsed it

## Are All Iterators Invalid After `erase` on a `std::vector`?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template