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

C++ Deque insert() Usage and Example

C++ Deque (Double-ended Queue)

C ++ The Deque insert() function inserts a new element before the specified position pos, and the size of the container increases with the number of inserted elements. The insertion of elements can be done from the front or 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: The position where the new element is to be inserted.

val: The new value to be inserted.

n: The number of values to insert.

(first, last): It defines the range of elements to be inserted.

Return value

It returns the iterator to the newly constructed element.

Example1

Let's look at 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, the insert() function inserts a new element at the second position, that is, "C" ++".

Example2

Let's look at 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, the insert() function inserts the string "" at the second and third positions twice 5element.

C++ Deque (Double-ended Queue)