Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector erase iterator

I have this code:

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;     } } 

"A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence."

This code crashes, but if I use the if(it == res.end()) portion and then return, it works. How come? Does the for loop cache the res.end() so the not equal operator fails?

like image 237
hidayat Avatar asked Jan 10 '11 10:01

hidayat


People also ask

What does vector erase () do in C++?

The vector::erase() function is a function that is implemented in the vector class and used to remove elements one-by-one. This function erases the element from a desired position.

What happens to iterator after erase?

Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated. Only iterators and references to the erased elements are invalidated.


1 Answers

res.erase(it) always returns the next valid iterator, if you erase the last element it will point to .end()

At the end of the loop ++it is always called, so you increment .end() which is not allowed.

Simply checking for .end() still leaves a bug though, as you always skip an element on every iteration (it gets 'incremented' by the return from .erase(), and then again by the loop)

You probably want something like:

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

to erase each element

(for completeness: I assume this is a simplified example, if you simply want every element gone without having to perform an operation on it (e.g. delete) you should simply call res.clear())

When you only conditionally erase elements, you probably want something like

for ( ; it != res.end(); ) {   if (condition) {     it = res.erase(it);   } else {     ++it;   } } 
like image 131
Pieter Avatar answered Oct 15 '22 06:10

Pieter