Insert an Element at the Given Index

Syntax of insert() in Vector

vector_name.insert (position, val);

Parameters

The function accepts two parameters specified below:

  • position It specifies the iterator which points to the position where the insertion is to be done.
  • val It specifies the value to be inserted.

Example of insert() in vector

C++




// C++ program to illustrate the function of
// vector_name.insert(position,val)
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Initialising the vector
    vector<int> vector_name{ 1, 2, 3, 4, 5 };
  
    // Printing out the original vector
    cout << "Original vector :\n";
    for (auto x : vector_name)
        cout << x << " ";
    cout << "\n";
  
    // Inserting the value 100 at position 3(0-based
    // indexing) in the vector
    vector_name.insert(vector_name.begin() + 3, 100);
  
    // Printing the modified vector
    cout << "Vector after inserting 100 at position 3 :\n";
    for (auto x : vector_name)
        cout << x << " ";
    cout << "\n";
  
    // Inserting the value 500 at position 1(0-based
    // indexing) in the vector
    vector_name.insert(vector_name.begin() + 1, 500);
  
    // Printing the modified vector
    cout << "Vector after inserting 500 at position 1 :\n";
    for (auto x : vector_name)
        cout << x << " ";
    return 0;
}
  
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Output

Original vector :
1 2 3 4 5 
Vector after inserting 100 at position 3 :
1 2 3 100 4 5 
Vector after inserting 500 at position 1 :
1 500 2 3 100 4 5 

vector insert() Function in C++ STL

std::vector::insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.

Time Complexity – Linear, O(N)

The insert function is overloaded to work on multiple cases which are as follows:

  1. Insert an element at the given index.
  2. Insert an element multiple times.
  3. Insert a range of elements at the given index.

Similar Reads

1. Insert an Element at the Given Index

Syntax of insert() in Vector...

2. Insert Multiple Elements at Given Index

...

3. Insert the Range of Elements at Given Index

Syntax of insert() in Vector...