< Previous | Contents | Next >

Using the erase() Vector Member

Function

Next I remove an item from the heros inventory. However, this time I dont remove the item at the end of the sequence; instead, I remove one from the middle.

inventory.erase((inventory.begin() + 2));

One form of the erase() member function removes an element from a vector. You supply one argument to this version of erase()the iterator that references the element you want to remove. In this case, I passed (inventory.begin() + 2), which is equal to the iterator that references the third element in inventory. This removes the string object equal to "armor". As a result, all of the following elements will move up by one. This version of the erase() member function

Using Algorithms 131


returns an iterator that references the element after the element that was removed. In this case, I dont assign the returned iterator to a variable.

Tra p

image

Calling the erase() member function on a vector invalidates all of the iterators that reference elements after the removal point because all of the elements after the removal point are shifted up by one.

image


Next I show the contents of the vector to prove the removal worked.