Tutorials  /  Linux Basics

Understanding Vector insert() in C++

Ccentron Redaktion · January 2024 ·5 min read ·Linux Basics, Tutorial

Introduction

In this tutorial, we are going to learn about vector insert() in C++. As well as look at how it works and can be used to accomplish the insertion operation in different ways with examples.

VM

Matching infrastructure at centron

No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

The vector::insert() function in C++

Basically, the vector::insert() function from the STL in C++ is used to insert elements or values into a vector container. In general, the function returns an iterator pointing to the first of the inserted elements.

Using the insert() Function on Vectors

The insert() method can be used to insert single or multiple elements into a given vector in different ways, for different cases. We can insert a single value at our desired position, we can even insert multiple values into the vector at once, and even we can insert a bunch of values from another vector to it.

So, let us see how we can do that with ease.

1. Insert a single value into a Vector

We can directly pass an iterator pointing to our desired position and the value to be inserted there to the insert() function to modify a vector.

Look carefully at the example below, here we try to insert a value 10 at the beginning of the vector.

Code
#include
#include
using namespace std;
int main()
{  
    vector<int> vec {1,2,3,4,5};

    cout<<"Intially vector: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }

    vec.insert(vec.begin(),10); //Inserting 10 to the vector

    cout<<"\n\nThe modified vector is: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }
    return 0;
}

Output:

Code
Initially vector: 1 2 3 4 5
The modified vector is: 10 1 2 3 4 5

Here,

  • Firstly we initialize a vector, vec. And print the same,
  • Then we call the insert() function on the vector vec with parameters vec.begin() and 10(new value). Note, here vec.begin() returns an iterator pointing to the start of the vector,
  • After the insertion has been done we print the new vector using a simple for loop to see the resultant vector.

2. Insert the same value Multiple times

We can also insert multiple values to a vector at once using the insert() function. This can be done by passing an iterator pointing to our starting position where we want to insert, the number of times the value is going to repeat, and at last the value.

The example below illustrates the use properly.

Code
#include
#include
using namespace std;
int main()
{  
    vector<int> vec {10,20,30,40};

    cout<<"Initially vector: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }

    vec.insert(vec.end(),3,100); //Inserting 100, 3 times to the vector

    cout<<"\n\nThe modified vector is: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }
    return 0;
}

Output:

Code
Initially vector: 10 20 30 40
The modified vector is: 10 20 30 40 100 100 100

Here,

  • We initialize our vector vec and print the same,
  • Then we pass an iterator pointing to the end of the vector, as returned by vec.end(), 3(the number of times we want the value to repeat), and the value 100 to the insert() function.
  • In this way, as we can observe from the output, 100 is inserted thrice at the end of the vector, vec.

3. Insert Another Vector

Further, we can also insert elements of another vector to our old vector. Just we need to pass an iterator pointing to the position in our vector where we need to insert another vector. Along with that, the iterators pointing to the starting and end of the second vector.

Let us take a small example to understand the working.

Code
#include
#include
using namespace std;
int main()
{  
    vector<int> vec {2,4,6,8};
    vector<int> vec2 {1,3,5,7};
    cout<<"Initially first vector: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }
    cout<<"\nInitially second vector: ";
    for(auto i=vec2.begin(); i<vec2.end(); i++)
    {
        cout<<" "<<*i;
    }

    //Inserting vec2 at the beginning of the vec vector
    vec.insert(vec.begin(),vec2.begin(),vec2.end());

    cout<<"\n\nThe modified vector is: ";
    for(auto i=vec.begin(); i<vec.end(); i++)
    {
        cout<<" "<<*i;
    }
    return 0;
}

Output:

Code
Initially first vector: 2 4 6 8
Initially second vector: 1 3 5 7
The modified vector is: 1 3 5 7 2 4 6 8

Here, vec and vec2 are two vectors. Out of which vec2 is the one whose elements we need to insert into the vector, vec. We call the insert() function with appropriate parameters as mentioned earlier. This modifies our vector vec, resulting in the insertion of the second vector elements at the beginning.

Conclusion

So, in this tutorial, we explained the working as well as the use of the vector insert() function from the STL in C++. For better understanding, we recommend trying the above code snippets yourselves.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren