deque emplace in C++ STL
Last Updated :
24 Jun, 2021
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 parameters:
- 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:
CPP
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque< int > sample = { 2, 3, 4, 5 };
deque< int >::iterator itr;
sample.emplace(sample.begin(), 1);
for (itr = sample.begin(); itr != sample.end(); ++itr)
cout << *itr << " " ;
cout << endl;
return 0;
}
|
Example-2:
CPP
#include <deque>
#include <iostream>
using namespace std;
int main()
{
deque< char > sample = { 'G' , 'E' , 'K' , 'S' };
deque< char >::iterator itr = sample.begin();
++itr;
sample.emplace(itr, 'E' );
for (itr = sample.begin(); itr != sample.end(); ++itr)
cout << *itr;
cout << endl;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...