C++ Standard Library C++ STL Library

C++ <deque> - emplace() Function



The C++ deque::emplace function is used to insert new element at specified position in a deque. Each insertion of element increases the deque container size by one.

Syntax

template <class... Args>
iterator emplace (const_iterator position, Args&&... args);

Parameters

position Specify the position in the deque where the new element need to be inserted.
args Arguments forwarded to construct the new element.

Return Value

An iterator that points to the newly emplaced element.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the deque::emplace function is used to insert new element at specified position in a deque MyDeque.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<int> MyDeque{10, 20, 30, 40, 50};
  
  //insert a new element at position = 3
  MyDeque.emplace(MyDeque.begin()+2, 100);

  //insert a new element at position = 3
  MyDeque.emplace(MyDeque.begin()+2, 200);

  //insert a new element at the end of the deque
  MyDeque.emplace(MyDeque.end(), 300);

  cout<<"MyDeque contains: ";
  for(int i=0; i< MyDeque.size(); i++)
    cout<<MyDeque[i]<<" ";   

  return 0;
}

The output of the above code will be:

MyDeque contains: 10 20 200 100 30 40 50 300 

Example:

Lets see another example where the deque MyDeque contains string values.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<string> MyDeque{"JAN", "APR", "MAY"};
  
  //insert a new element at position = 2
  deque<string>::const_iterator it = MyDeque.emplace(MyDeque.begin()+1, "MAR");

  //insert a new element at position = 2
  MyDeque.emplace(it, "FEB");

  //insert a new element at the end of the deque
  MyDeque.emplace(MyDeque.end(), "JUN");

  cout<<"MyDeque contains: ";
  for(int i=0; i< MyDeque.size(); i++)
    cout<<MyDeque[i]<<" ";   

  return 0;
}

The output of the above code will be:

MyDeque contains: JAN FEB MAR APR MAY JUN 

❮ C++ <deque> Library