C++ emplace_back
This function is employed to add a new element to the end of the vector, thereby expanding the size of the vector container.
Syntax
Consider a vector 'v'. Syntax would be :
v.emplace_back(args);
Parameter
Parameters: Arguments passed to instantiate the new element.
Return value
It does not return any value.
Example 1
Let's see a simple example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<char> v{'C','+'};
v.emplace_back('+');
for(int i=0;i<v.size();i++)
cout<<v[i];
return 0;
}
Output:
In this instance, the size of the vector 'v' expands by appending a new character value at the vector's end through the emplace_back method.
emplace vs insert
The insert method is employed for duplicating objects into the vector, whereas emplace is utilized to create objects directly within the vector, thereby preventing redundant operations.
Example 2
Let's see another simple example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
v.emplace_back(6);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
return 0;
}
Output:
1 2 3 4 5 6
In this instance, the emplace_back method is employed to append a new integer value to the vector, specifically after the final element.