deque emplace in C++ STL

Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.

emplace() function inserts a new element just before the specified position and the size of the container is increased by one.

Syntax :

iterator emplace(const_iterator position, value_type val);

Parameters: This method accepts following paramters:

  • position: It defines the position before which the new element is to be inserted.
  • val: New value which is to be inserted.

Return value : It returns an iterator to the newly constructed element.

Below examples illustrate this method:

Example-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <deque>
#include <iostream>
using namespace std;
  
int main()
{
  
    // initialization of deque named sample
    deque<int> sample = { 2, 3, 4, 5 };
  
    // initializing an iterator
    deque<int>::iterator itr;
  
    // adding 1 at the first position in
    // the sample as itr points to
    // first position in the sample
    sample.emplace(sample.begin(), 1);
  
    // Looping the whole
    for (itr = sample.begin(); itr != sample.end(); ++itr)
        // sample for printing
        cout << *itr << " ";
  
    cout << endl;
    return 0;
}

chevron_right


Output:

1 2 3 4 5

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <deque>
#include <iostream>
using namespace std;
int main()
{
  
    // initialization of deque named sample
    deque<char> sample = { 'G', 'E', 'K', 'S' };
  
    // initialising an iterator
    deque<char>::iterator itr = sample.begin();
  
    // incrementing the iterator by one place
    ++itr;
  
    // adding E at the second position in
    // the sample as itr points to
    // second position in the sample
    sample.emplace(itr, 'E');
  
    // Looping the whole
    for (itr = sample.begin(); itr != sample.end(); ++itr)
  
        // sample for printing
        cout << *itr;
  
    cout << endl;
    return 0;
}

chevron_right


Output:

GEEKS


My Personal Notes arrow_drop_up

Problem solver, self learner, avid reader and chess lover )

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.