hidayat hidayat -4 years ago 75
C++ Question

vector erase iterator

I have this code:

int main()
vector<int> res;
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()) and then returns it works. How come?
Does the for loop cash the res.end() so the not equal operator fails?

Answer Source

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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download