The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.
Syntax:
template
iterator vector_name.emplace (const_iterator position, element);
Parameter:
The function accepts two mandatory parameters which are specified as below:
- position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
- element- It specifies the element to be inserted in the vector container.
Return value: The function returns an iterator that points to the newly inserted element.
Complexity: Linear
Below programs illustrates the above function:
Program 1:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30 };
auto it = vec.emplace(vec.begin(), 15);
cout << "The vector elements are: " ;
for ( auto it = vec.begin(); it != vec.end(); ++it)
cout << *it << " " ;
return 0;
}
|
Output: The vector elements are: 15 10 20 30
Program 2:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30 };
auto it = vec.emplace(vec.end(), 16);
cout << "The vector elements are: " ;
for ( auto it = vec.begin(); it != vec.end(); ++it)
cout << *it << " " ;
return 0;
}
|
Output: The vector elements are: 10 20 30 16
Program 3:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30 };
auto it = vec.emplace(vec.begin() + 2, 16);
cout << "The vector elements are: " ;
for ( auto it = vec.begin(); it != vec.end(); ++it)
cout << *it << " " ;
return 0;
}
|
Output: The vector elements are: 10 20 16 30
Additional Related Links: emplace_front( ) and emplace_back( )
Regular insertion using shift operation in arrays V/s emplace( ) function :
a) If want to insert an element at some specific position between the first and last index, we have to shift all the elements next to that specific index. So, if want to keep our code precise so emplace( ) would be a good choice. In terms of Time Complexity both take the same linear time which is directly dependent on the number of shift operations.
Ex:
C++
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main() {
array< int ,6> a={1,2,4,5};
vector< int > v={1,2,4,5};
for ( int i=3;i>=0;i--)
{
if (i!=1)
a[i+1]=a[i];
else {
a[i+1]=3; break ;
}
}
cout<< "Content of a: " ;
for ( int i=0;i<5;i++)
cout<<a[i]<< " " ;
v.emplace( v.begin() + 2 , 3);
cout<< "\nContent of v: " ;
for ( int i=0;i<v.size();i++)
cout<<v[i]<< " " ;
return 0;
}
|
OutputContent of a: 1 2 3 4 5
Content of v: 1 2 3 4 5