C++ Vector emplace
This function adds a new element before the specified position pos, thereby expanding the size of the vector container.
Syntax
Consider a vector 'v'. Syntax would be:
Iterator it=v.emplace(pos,args);
Parameter
It specifies the placement where the new element will be added.
Arguments: Parameters passed to instantiate the new element.
Return value
It provides an iterator pointing to the element that was just added.
Example 1
Let's see a simple example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
cout<<"Elements of vector v are :";
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<'\n';
cout<<"After adding two elements, elements are :";
vector<int>::iterator it=v.emplace(v.begin()+2,8);
v.emplace(it,9);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
return 0;
}
Output:
Elements of vector v are :1 2 3 4 5
After adding two elements, elements are :1 2 9 8 3 4 5
In this instance, the size of the vector container expands by employing the emplace method.
Example 2
Let's see a simpleanother example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v{"mango","apple","banana"};
v.emplace(v.begin()+2,"strawberry");
for(int i=0;i<v.size();i++)
std::cout<< v[i] << " ";
return 0;
}
Output:
Mango apple strawberry banana
In this instance, the vector container's size grows as a new string is inserted into the vector utilizing the emplace method.