< Previous | Contents | Next >

Using the insert() Vector Member

Function

Next I add a new item to the heros inventory. This time, though, I dont add the item to the end of the sequence; instead, I insert it at the beginning.

inventory.insert(inventory.begin(), "crossbow");

One form of the insert() member function inserts a new element into a vector just before the element referred to by a given iterator. You supply two arguments to this version of insert()the first is an iterator, and the second is the element to be inserted. In this case, I inserted "crossbow" into inventory just before the first element. As a result, all of the other elements will move down by one. This version of the insert() member function returns an iterator that references the newly inserted element. In this case, I dont assign the returned iterator to a variable.


Tra p

image

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

image


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