C++ Deque insert
The insert function in C++ Deque adds a new element just prior to the specified position pos, effectively increasing the container's size by the number of elements inserted. The insertion can occur either at the front or the back of the deque.
Syntax
iterator insert(iterator pos, value_type val);
void insert(iterator pos, int n, value_type val);
void insert(iterator pos, InputIterator first,InputIterator last);
Parameter
The pos parameter indicates the position where the new element will be inserted.
val : New value to be inserted.
n : Number of times the value to be inserted.
The pair (first, last) specifies the boundary within which the elements will be added.
Return value
It provides an iterator pointing to the newly created element.
Example 1
Let's see a simple example
#include <iostream>
#include<deque>
using namespace std;
int main()
{
deque<string> language={"java",".net","C"};
deque<string>::iterator itr=language.begin();
++itr;
language.insert(itr,"C++");
for(itr=language.begin();itr!=language.end();++itr)
cout<<*itr<<" ";
return 0;
}
Output:
java C++ .net C
In this instance, the insert method adds a new element, specifically "C++", at the second index.
Example 2
Let's see a simple example
#include <iostream>
#include<deque>
using namespace std;
int main()
{
deque<int> k={1,2,3,4};
deque<int>::iterator itr=k.begin();
++itr;
k.insert(itr,2,5);
for(itr=k.begin();itr!=k.end();++itr)
std::cout << *itr <<" ";
return 0;
}
Output:
1 5 5 2 3 4
In this instance, the insert method adds the element '5' two times at the second and third positions.