INSERT()
This function is used to add one or more elements at a specific position within the vector. Unlike push_back()
, which only appends elements to the end, insert()
can place elements anywhere in the vector, shifting existing elements to make room. You can insert a single element, multiple copies of an element, or even a range of elements from another container or iterator. The function requires an iterator indicating the insertion point, and it returns an iterator pointing to the first of the newly inserted elements. Since inserting elements in the middle may require moving subsequent elements, this operation can be less efficient than appending at the end, especially for large vectors. It is a versatile tool when you need precise control over element positioning in a dynamic array.
vectorName.insert(positionIterator, value);
* positionIterator: Where you want to insert the value (e.g., vec.begin() + index).
* value: The new element to be inserted at that position.
EXAMPLE 1
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Step 1: Initialize a vector with initial numbers
vector<int> numbers = {10, 20, 40, 50};
// Step 2: Create another vector with values to insert
vector<int> toInsert = {25, 30, 35};
// Step 3: Insert multiple elements at position index 2 (before 40)
numbers.insert(numbers.begin() + 2, toInsert.begin(), toInsert.end());
// Step 4: Print updated vector using normal for loop
cout << "Updated numbers:" << endl;
for (int i = 0; i < 7; i++) { // We know the final size is 7
cout << numbers[i] << " ";
}
return 0;
}
EXAMPLE 2
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
// 1. Insert a single element at position 2 (3rd element)
v.insert(v.begin() + 2, 99); // v = {1, 2, 99, 3, 4, 5}
// 2. Insert multiple copies of an element at position 0
v.insert(v.begin(), 3, 7); // insert 7 three times at the start
// v = {7, 7, 7, 1, 2, 99, 3, 4, 5}
// 3. Insert a range of elements from another vector
std::vector<int> other = {10, 20, 30};
v.insert(v.end(), other.begin(), other.end()); // insert at the end
// v = {7, 7, 7, 1, 2, 99, 3, 4, 5, 10, 20, 30}
// Print the result
for(int n : v) {
std::cout << n << " ";
}
return 0;
}
Last updated