English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ List insert() Usage and Example

C++ List (List)

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

Syntax

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 where the new element is to be inserted.

value:The value to be inserted.

n:The number of occurrences of the value.

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

Return value

It returns an iterator pointing to the newly constructed element.

Example1

Let's see a simple 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:

51234

In this example, the iterator points to the first element of the list. Therefore, the insert() function is used to insert5Insert it before the first element of the list.

Example2

Let's see a simple example, given n.

#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:

java java C is a language

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

Example3

Let's see a simple 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:

6 7 8 9 1 2 3 4 5

In this example, the list li is given1range (first, last). Therefore, the insert() function inserts elements within this range in the list li.

C++ List (List)