This tutorial will discuss how to insert an element into a vector in C++.

In C++, we often encounter situations where we want to insert an element into a vector at a position other than the end. For that, the vector class provides an insert() function, which has several overloaded versions. Let’s discuss one of them.

To insert a single element within a vector, you can use the insert() function with two arguments:
1. An iterator pointing to the position where we want to insert the element.
2. The value that we want to insert.

For instance, if we want to insert the value 12 at the 3rd position in the vector, we first need an iterator pointing to this position. We can achieve this by calling the begin() function of the vector, which returns an iterator pointing to the first element. To get to the 3rd position, we simply add 2 to this iterator (keeping in mind that indexing starts from 0). Then, we pass this iterator as the first argument to the insert function and 12 as the second argument. After this operation, the value 12 will be inserted at the 3rd position in the vector.

The insert() function returns an iterator pointing to the newly inserted element.

This is how we can insert a single value into a vector using the insert function.

std::vector<int> vecObj = {11, 22, 33, 44};
auto it = vecObj.begin() + 2;
vecObj.insert(it, 12);

Here, we added a value 12 at the third position in the vector. After this operation, the contents of vec will be: 11, 22, 12, 33, 44.

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vecObj = {11, 22, 33, 44};

    // Get an iterator to third element in vector
    auto it = vecObj.begin() + 2;

    // Insert value 12 into the vector as 3rd element
    vecObj.insert(it, 12);

    // Print the contents of vector
    for (const auto &num : vecObj)
    {
        std::cout << num << ", ";
    }
     std::cout << "n";
    return 0;
}

Output

11, 22, 12, 33, 44,

Summary

Today, we learned how to insert an element into a vector in C++.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.