Vectors insert: The below code is an example of a vector insert function. It may help the beginners.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = {1, 2, 4, 5};
// Insert a single element at position 2
v.insert(v.begin() + 2, 3);
// v = {1, 2, 3, 4, 5}
// Insert multiple copies of a value
v.insert(v.begin() + 1, 3, 9);
// Inserts three 9s at index 1
// v = {1, 9, 9, 9, 2, 3, 4, 5}
// Insert a range of elements from another vector
std::vector<int> other = {7, 8};
v.insert(v.end(), other.begin(), other.end());
// Appends 7 and 8
// v = {1, 9, 9, 9, 2, 3, 4, 5, 7, 8}
// Insert using an initializer list at the beginning
v.insert(v.begin(), {10, 11}); // Inserts 10 and 11 at the start
// v = {10, 11, 1, 9, 9, 9, 2, 3, 4, 5, 7, 8}
// Print the final result
std::cout << "Vector contents: ";
for (int val : v)
{
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}

Leave a comment