Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Erasing last item of a vector with iterator? 1

Status
Not open for further replies.

Sen7inel

IS-IT--Management
Feb 14, 2001
90
FI
Hi,

I guess this is pretty basic, but I can't seem to sort this out right now: I'm going thru a vector with an iterator, and if get a match, want to erase the item. Something like this:
Code:
for (vector<int>::iterator i = v.begin(); i != v.end(); ++i)
  if ((*i) == 0)
    v.erase(i);
Now, if the last item is erased, the iteration goes thru one more time, with the size of v being 0, and me getting an access violation. i is not end(). How is this supposed to be done without having to check size() or empty()?
 
For your specific example, try:
Code:
remove( v.begin(), v.end(), 0 );

If you want to test for a more complex condition than equality, you can create a function object and use it in [tt]remove_if[/tt].

Both [tt]remove[/tt] and [tt]remove_if[/tt] are in the [tt]<algorithm>[/tt] header, and in the [tt]std[/tt] namespace.
 
What a lot of people do not realize is that erase returns the next iterator. If you want a loop, your loop should look like
Code:
for (vector<int>::iterator i = v.begin(); i != v.end();)
  if ((*i) == 0)
    i = v.erase(i);
  else
     ++i;
 
iterator erase(iterator it);
iterator erase(iterator first, iterator last);

The first member function removes the element of the controlled sequence pointed to by it. The second member function removes the elements of the controlled sequence in the range [first, last). Both return an iterator that designates the first element remaining beyond any elements removed, or end() if no such element exists.

xwb: I don't see why the original form won't work if the last iterator that erase() returns is end()?
 
The original code might "work", but really it is undefined behavior because even if the element that is erased is the last element in the vector, the for loop still increments the iterator after the call to erase and before it checks it against v.end(). The iterator was invalidated after the call to erase, and so incrementing it is undefined.
 
After the ++i, i = v.end () + 1. You will never reach the condition i != v.end ().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top