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++
// C++ Program to show how to Insert into a Vector Using an // Iterator #include <iostream> #include <vector> using namespace std; // Driver Code int main() { vector< int > myVector = { 1, 2, 3, 4, 5 }; // Insertion in the middle using iterator vector< int >::iterator it = myVector.begin() + 2; // insertion myVector.insert(it, 10); // Display the vector for ( int i = 0; i < myVector.size(); i++) { cout << myVector[i] << " " ; } return 0; } |
1 2 10 3 4 5
Time Complexity: O(N), where N is the size of the vector.
Sapce Complexity: O(1)
How to Insert into Vector Using Iterator in C++?
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