2.1.3 Inserting into a Vector

There are two basic ways to add values to a vector, using the push_back command and the insert command.

  • v.push_back(value) - Push back will insert a new value at the end of the vector.

  • v.insert(iterator, value) - Insert is used to add a value at a specific index. Existing values shift to the right (higher index) by one

Push Back

Push back is the standard command that adds the new value to the end of the vector.

vector<int> nums {5, 10}
// Current vector [5, 10]
nums.push_back(15);
// Current vector [5, 10, 15]

Insert

Insert is used to add a new value at a particular index, but its use is a little more tricky. Instead of using an index value directly, you need to use an iterator. You will learn more about iterators later, but for now, it is important to know that it is a special variable type that holds an index position for a data structure like a vector. In this case, it will hold the position for the index where we want to insert into.

To use the iterator, you must first create it and assign it to the beginning of your vector. When declaring the iterator, you need to reference the vector type by using angle brackets <> followed by a double colon :: and then the keyword iterator. You then assign it to the beginning of the vector using the begin() command. For example, to create an iterator for the nums vector it would look like this:

vector<int>::iterator itr = nums.begin();

The iterator variable name can be anything. In this example, itr is used.

Once created, you can then use the iterator in the insert command by adding to the iterator a value corresponding to the index to insert into. For example, if you want to insert at index 2, you would use itr + 2.

Here is a more complete example:

vector<int> nums {5, 10, 15, 20}
// Current vector [5, 10, 15, 20]
vector<int>::iterator itr = nums.begin();
nums.insert(itr + 2, 12);
// Current vector [5, 10, 12, 15, 20]

Notice how the value of 12 was inserted at index 2 and the other values were moved to the right with a higher index value.

Once you insert into the vector, the iterator is no longer valid. You need to update it before using it again.

Last updated