How to Insert into Vector Using Iterator in C++?
Last Updated :
28 Feb, 2024
In C++, a vector is a dynamic array that can grow and shrink in size as needed. Vectors are sequence containers representing arrays that can change in size. In this article, we will learn how to insert elements into a vector using an iterator in C++.
Example:
Input:
myVector = {10,20,30};
Output:
Vector after insertion: 10 20 100 30
Insertion into Vector using Iterator in C++
To insert elements into a vector using an iterator in C++ STL, you can use the insert()
function that takes the iterator and the element to be inserted. This function will insert the given element at the position referred by the iterator and all the elements to the right of that position will be shifted by one place.
C++ Program to Insert into Vector Using Iterator
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
vector< int >::iterator it = myVector.begin() + 2;
myVector.insert(it, 10);
for ( int i = 0; i < myVector.size(); i++) {
cout << myVector[i] << " " ;
}
return 0;
}
|
Time Complexity: O(N), where N is the size of the vector.
Sapce Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...