< Previous | Contents | Next >
Using the erase() Vector Member
Next I remove an item from the hero’s inventory. However, this time I don’t 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
returns an iterator that references the element after the element that was removed. In this case, I don’t assign the returned iterator to a variable.
Tra p
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.
Next I show the contents of the vector to prove the removal worked.