List Insert Function - C++ Programming Tutorial
C++ Course / Dynamic Programming / List Insert Function

List Insert Function

BLUF: Mastering List Insert Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: List Insert Function

C++ is renowned for its efficiency. Learn how List Insert Function enables low-level control and high-performance computing in the tutorial below.

C++ List insert

The insert function in C++ adds a new element right before the specified position, expanding the list container's size by the number of newly added elements.

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

It specifies the location where the new element will be inserted.

value : The value to be inserted.

n : Number of times the value to be occurred.

Specifies the range of elements to be added at the specified position pos within a container.

Return value

It yields an iterator referencing the recently created 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 instance, the iterator is directed to the initial element in the list. As a result, the number 5 is added prior to the first element of the list by employing the insert method.

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 instance, the insert method adds the string "java" twice prior to the initial element in 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 scenario, the range(first, last) within the list li1 is specified. Consequently, the insert method incorporates the elements within this specified range into the list li.

Input Required

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

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience