C++ Deque insert
C++ Deque insert function inserts new element just before the specified position pos and the size of the container increases by the number of elements are inserted. Insertion of an element can be done either from front or from the back.
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
pos : Position before which the new element is to be inserted.
val : New value to be inserted.
n : Number of times the value to be inserted.
(first,last) : It defines the range of the elements which are to be inserted.
Return value
It returns an iterator to the newly constructed 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 example, insert function inserts new element i.e "C++" at the second position.
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 example, insert function inserts '5' element twice at second and third position.