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

Vector Emplace Back Function

BLUF: Mastering Vector Emplace Back 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 Back Function

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

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 :

Example

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.

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.

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:

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.

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