In this article we will discuss how to insert one or multiple elements at specific index in vector.

Vector provides different overloaded version of member function insert() , to insert one or more elements in between existing elements.
Let’s discuss them in detail,

Inserting a single element at specific position in vector

We are going to use first overloaded version of Vector’s insert() function i.e.

It Inserts a copy of give element “val”, before the iterator position “pos” and also returns the iterator pointing to new inserted element.

Let’s understand by example,

Suppose we have a vector of int i.e.

Now we want to insert an element at index position 4th (In vector position index start from 0),

Vector’s contents will be now,

Inserting an element in vector will increase the vector size by 1.
As in vector all elements are stored at continuous memory locations, so inserting an element in between will cause all the elements in right to shift or complete reallocation of all elements.

Inserting multiple elements or a range at specific position in vector

Some times we encounter a situation where we want to insert multiple elements in vector at specific position. These multiple elements can from another vector , array or any other container.

For this, vector provides an overloaded version of insert() function to insert multiple elements i.e.

It inserts the elements in range from [first, end) before iterator position pos and returns the iterator pointing to position first newly added element.

Let’s understand by an example,

Suppose we have 2 vectors of strings i.e.

Now insert all the elements in vec2 at position 3 in vec1 i.e.

Contents of vec1 will be now,

Inserting multiple elements using Initializer list

Another overloaded version of vector’s insert() function is as follows,

It copies all the elements in given initializer list before given iterator position pos and also returns the iterator of first of the newly added elements.

Suppose we have vector of int i.e.

Let’s add all elements in initialisation list to the existing vector i.e.

Contents of vecOfInts will be now,

vector.insert() and Iterator invalidation

Inserting elements in vector will cause existing elements to shift places or sometimes complete reallocation, which will invalidates all the existing iterators.

Complete example is as follows,


To Compile the above example in linux use following command,

g++ –std=c++11 example.cpp

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.