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