Vector insert function in C++

Here we will learn about the insert() function present in C++ STL.

insert() function is used to insert a new element in a vector.

By taking two arguments:

  1. The iterator of the position where the new element is to be inserted.
  2. The element to be inserted.

See the below implementation:

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<int>arr{1,2,3,5,6};
    
    arr.insert(arr.begin()+3,4);
    for(auto&it:arr)cout<<it<<" ";
    cout<<endl;
    return 0;
}
Output: 1 2 3 4 5 6

By taking three arguments:

It is an overloaded function so can work for three arguments as well :

Type 1: One iterator and two values are passed-

  1. Iterator: The starting position of elements to be inserted.
  2. First Value: Number of times to be repeated the inserted value.
  3. Second Value: The value to be inserted.
#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<int>arr{1,2,3,5,6};
    
    arr.insert(arr.begin()+3,3,4);

    for(auto&it:arr)cout<<it<<" ";
    cout<<endl;
    return 0;
}
Output:1 2 3 4 4 4 5 6

Type 2: Three Iterators are passed –

  1. First Iterator: It indicates the starting position of insertion.
  2. Second Iterator: It indicates the starting position of elements to be copied.
  3. Third Iterator: It indicates the ending position of elements to be copied.

Here the elements starting from the second iterator to the third iterator are copied into the vector at the specified position.

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<int>arr{1,2,3,5,6};
    vector<int>arr1{0,8,12};
    
    // Elements from second array are copied to first array
    arr.insert(arr.begin()+3,arr1.begin(),arr1.end()-1);
    
    for(auto&it:arr)cout<<it<<" ";
    cout<<endl;
    return 0;
}
Output: 1 2 3 0 8 5 6

Leave a Reply

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