list insert() in C++

In this tutorial, we will learn about list insert() in C++.

The list insert() function in C++ inserts an element at any particular place on the list. This function takes three arguments namely the location to insert, the number of elements to insert and the value of the element to insert. If the number of elements to insert is not mentioned, then by default its value is 1.

This tutorial helps you to know the various ways in which insert() can be used as follows:

The syntax and functionality of insert() are illustrated below:

Syntax: list insert()

    #include <list>
    iterator insert( iterator loc, const TYPE& val );
    void insert( iterator loc, size_type num, const TYPE& val );
    template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );

The insert() function either inserts:

  • value before loc, returning an iterator to the element inserted,
  • num copies of value before loc, or
  • the elements from start to end before loc.

Implementation of insert() with a simple code:

#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main()
{
    vector<char> a; 
    for( int j=0; j < 10; j++ ) 
    { 
        a.push_back( j + 65 );
    } 
    vector<char>::iterator Iteratorname = a.begin();
    a.insert( Iteratorname, 4, 'D' ); 
    for( Iteratorname = a.begin(); Iteratorname != a.end(); Iteratorname++ ) 
    { 
        cout<< *Iteratorname; 
    }
    return 0;
}

Output:

DDDDABCDEFGHIJ

Program Description:

This program illustrates the use of insert(). The header files used for this program are #include <iostream> for input-output activities, #include <vector> because we are using vectors in our implementation of the list insert()  and #include <list> for the insert() function.

For this, create a vector first and fill it with the first ten characters of the alphabet ( ABCDEFGHIJ ). Then, insert four D’s into the vector and display the vector. It will give the output DDDDABCDEFGHIJ as shown above.

I hope this tutorial was helpful to know the syntactical as well as the implementation of the list insert() function in C++.

Thanks for reading. Happy learning folks!

Recommended blogs:
How to Sort a Vector of Pairs in C++
Vector erase() and clear() in C++

Leave a Reply

Your email address will not be published. Required fields are marked *