In this tutorial, we will learn about insert() member function of vector in C++.

In C++ STL, the std::vector class is a Sequential Container, which provides the flexibility of Dynamic Array that can be resized on the fly. A key member function of this class is insert(), which allows you to add elements at any specified position within the vector. This function is usefull for inserting elements in the middle of a vector or at any position in the vector.

Syntax of vector::insert()

The insert() member function in C++ has several overloaded versions. Here are the most commonly used ones:

iterator insert(iterator position, const T& value);
iterator insert(const_iterator position, T&& value);
iterator insert(const_iterator position, size_type count, const T& value);

In these function prototypes, T represents the type of elements stored in the vector, and iterator is the type of iterator used by the vector.

Parameters of vector::insert()

The insert() function has multiple parameters, depending on the overloaded version:

  1. position: The iterator position at which the new elements should be inserted.
  2. value: The value to be inserted. This can be either a lvalue reference (const T&) or an rvalue reference (T&&).
  3. count: The number of times the value should be inserted (only for the third overload).

Return Value of vector::insert()

The insert() function returns an iterator pointing to the first of the newly inserted elements.

Examples of vector::insert()

Example 1: Inserting a Single Element

In this example, we will create a vector of integers, and we will insert an element into this vector at index position 1 i.e. as the 2nd element of vector. To do this, we will pass an iterator pointing to that specific index position as the first argument and the value that we want to add as the second argument.

Let’s see the complete example,

#include <iostream>
#include <vector>

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

    // Inserting an element at the second position
    auto it = numbers.insert( numbers.begin() + 1, 22);

    std::cout << "Vector after insertion: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }

    return 0;
}

Output

Vector after insertion: 11 22 33 44

In this code, the number 22 is inserted at the second position of the vector numbers.

Explaination of the above code:

Basically, if you want to add an element at index position 1, which is essentially the second element, you can achieve this by pointing the iterator to that location. This can be done by calling the begin() function, which returns an iterator pointing to the first element of the vector. Then, we will increment the iterator by one (e.g., ++iterator) to move it to the second position. We will use this position as the first argument, and the element we want to add as the second argument. This way, it will insert the element at that specific location in the vector.

Example 2: Inserting Multiple Copies of an Element

Suppose we have a vector of integers,

std::vector<int> numbers = {11, 55};

In this example, we will insert three copies of the value 2 at the second position in this vector. To achieve this, we need to pass an iterator pointing to that particular location as the first argument. In this case, the iterator that will be positioned there is,

numbers.begin() + 1

Then, we will pass 3 as the second argument because we want to insert three copies of a value, and finally, we will pass 2 as the third argument, like this,

// Inserting three copies of 2 at the second position
numbers.insert(numbers.begin() + 1, 3, 2);

Essentially, this means we want to add the value 2 three times consecutively in the vector starting from index 1 i.e. starting from the 2nd position in vector.

Let’s see the complete example,

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {11, 55};

    // Inserting three copies of 2 at the second position
    numbers.insert(numbers.begin() + 1, 3, 2);

    std::cout << "Vector after insertion: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }

    return 0;
}

Output

Vector after insertion: 11 2 2 2 55

In this example, three copies of the number 2 are inserted starting from the second position of the vector.

Example 3: Handling the return value of insert() function

The vector::insert() function returns an iterator pointing to the first of the newly inserted elements. This example will show how to use the insert() function of a C++ vector and use the value returned by it:

Let’s see the complete example,

#include <iostream>
#include <vector>

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

    // Insert the value 99 at the beginning of the vector
    // and capture the iterator to the inserted element.
    std::vector<int>::iterator it = numbers.insert(numbers.begin(), 99);

    std::cout << "Vector after insertion:" << std::endl;
    for (const int& num : numbers) {
        std::cout << num << " ";
    }

    std::cout << "nValue inserted at the beginning: " << *it << std::endl;

    return 0;
}

Output

Vector after insertion:
99 11 22 33 44 55 
Value inserted at the beginning: 99

In this example:

  1. We create a std::vector called numbers containing some initial values.
  2. We use the insert() function to insert the value 99 at the beginning of the vector. The insert() function returns an iterator pointing to the inserted element.
  3. We then print the updated vector to see the result of the insertion.
  4. Finally, we print the value that was inserted at the beginning by dereferencing the iterator returned by insert().

As you can see, the insert() function inserts the value at the specified position and returns an iterator to the newly inserted element, allowing you to access or manipulate it if needed.

Summary

Today, we learned about the differet versions of vector::insert() function and how they can be used in adding elements at any desired position in a std::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.