Deque Insert Function - C++ Programming Tutorial
C++ Course / STL Queue & Stack / Deque Insert Function

Deque Insert Function

BLUF: Mastering Deque Insert Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Deque Insert Function

C++ is renowned for its efficiency. Learn how Deque Insert Function enables low-level control and high-performance computing in the tutorial below.

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

Example

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

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:

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

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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience