List Insert Function

C++ List insert

C++ List insert function inserts a new element just before the specified position. It increases the size of the list container by the number of elements added in the list.

Syntax

Example

iterator insert( iterator pos, const value_type value);
void insert( iterator pos, int n, const value_type value);
void insert( iterator pos, InputIterator first, InputIterator last);

Parameter

pos : It defines the position before which the new element is to be inserted.

value : The value to be inserted.

n : Number of times the value to be occurred.

( first,last) : It defines the range of the elements to be inserted at position pos.

Return value

It returns an iterator pointing to the newly constructed element.

Example 1

Let's see a simple example

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
   list<int> li={1,2,3,4};
   list<int>::iterator itr=li.begin();
   li.insert(itr,5);
   for(itr=li.begin();itr!=li.end();++itr)
   cout<<*itr;
   return 0;
}

Output:

In this example, iterator points to the first element of the list. Therefore, 5 is inserted before the first element of the list using insert function.

Example 2

Let's see a simple example when n is given.

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
   list<string> li={"C is a language"};
   list<string>::iterator itr=li.begin();
   li.insert(itr,2,"java ");
   for(itr=li.begin();itr!=li.end();++itr)
   cout<<*itr;
    return 0;
}

Output:

Output

java java C is a language

In this example, insert function inserts the string "java" 2 times before the first element of the list.

Example 3

Let's see a simple example

Example

#include <iostream>
#include<list>
using namespace std;

int main()
{
   list<int> li={1,2,3,4,5};
   list<int> li1={6,7,8,9};
   list<int>::iterator itr=li.begin();
   li.insert(itr,li1.begin(),li1.end());
   for(itr=li.begin();itr!=li.end();++itr)
{
   cout<<*itr;
   cout<<? ?;
              }                    
            return 0;
}

Output:

Output

6 7 8 9 1 2 3 4 5

In this example, range(first, last) of list li1 is given. Therefore, the insert function inserts the elements between this range in the list li.

Input Required

This code uses input(). Please provide values below: