How to insert an element into a specific position of a vector in C++

In this tutorial, we will learn how to insert a new element into a specific position of a vector in C++.

What is a Vector in C++

Vectors are just like arrays but there is a basic difference between both of them i.e. vectors are dynamic whereas arrays are not.

Header File for vector is:


To insert a vector we use insert function, which inserts new elements in the list.
Syntax is:

vector.insert(position of element,element)

Insertion of element into a specific position of a vector in C++

Now let us write the code to illustrate the same.

using namespace std;
int main()
{ vector<int>vec{12,34,48,53,69};
  cout<<"Vector Before Insertion"<<endl;
  for(int i=0;i<vec.size();i++)
        cout<<vec[i]<<" ";
 vec.insert(vec.begin()+3, 95) ;
 cout<<"\nVector After Insertion"<<endl;
 for(int i=0;i<vec.size();i++)
        cout<<vec[i]<<" ";


Vector Before Insertion
12 34 48 53 69
Vector After Insertion
12 34 48 95 53 69


In this code, first of all, we declared the vector containing some values in it. Then we printed the original vector before the insertion of a new element at a specific location.
vec.size()  will calculate the length of the vector.
vec.begin() inserts the element in the beginning so we add the index number with it where we want to add the element. Here position according to the syntax is vec.begin()+ index number.
After inserting the element we need to print the vector again in the output which can be done easily by using for loop.

Altogether insertion in the vector can be done easily by using the code given above, just remember the syntax and follow the code. It is quite similar to insertion in the array except for the syntax.

I hope you can try this to solve your problem.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *