Home > Backend Development > C++ > How to Safely Erase Elements from a C Vector While Iterating?

How to Safely Erase Elements from a C Vector While Iterating?

Mary-Kate Olsen
Release: 2024-12-05 04:31:09
Original
418 people have browsed it

How to Safely Erase Elements from a C   Vector While Iterating?

Vector Eradication with Erasing Iterators

In programming, traversing and manipulating data structures efficiently is crucial. Vectors, a popular dynamic container in C , provide flexibility and growth capabilities. However, erasing elements while iterating them can lead to unexpected outcomes.

Consider this example:

int main()
{
    vector<int> res;
    res.push_back(1);
    vector<int>::iterator it = res.begin();
    for( ; it != res.end(); it++)
    {
        it = res.erase(it);
        //if(it == res.end())
        //  return 0;
    }
}
Copy after login

The code above aims to erase all elements from the vector 'res' while iterating through it. However, it encounters an error when erasing the last element. This is because the iterator returned by 'res.erase(it)' points to the next valid element, which would be 'res.end()' in this case.

To resolve this issue, one can use a while loop without the conditional statement, like:

while (it != res.end()) {
    it = res.erase(it);
}
Copy after login

This ensures that the loop continues until all elements have been erased.

Alternatively, if you only need to erase specific elements based on some condition, you can use the following approach:

for ( ; it != res.end(); ) {
  if (condition) {
    it = res.erase(it);
  } else {
    ++it;
  }
}
Copy after login

Remember, when using iterators for vector manipulation, it's vital to understand how 'res.erase(it)' operates and to adjust the loop accordingly to prevent unexpected behaviors.

The above is the detailed content of How to Safely Erase Elements from a C Vector While Iterating?. 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