Vector Emplace Function - C++ Programming Tutorial
C++ Course / STL Vector / Vector Emplace Function

Vector Emplace Function

BLUF: Mastering Vector Emplace Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Vector Emplace Function

C++ is renowned for its efficiency. Learn how Vector Emplace Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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.

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:

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.

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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience