C++ Standard Library C++ STL Library

C++ <vector> - emplace_back() Function



The C++ vector::emplace_back function is used to insert new element at the end of the vector, after the current last element. Each insertion of element increases the vector container size by one. This may cause a reallocation when the vector size surpasses the vector capacity.

Syntax

template <class... Args>
void emplace_back (Args&&... args);

Parameters

args Arguments forwarded to construct the new element.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::emplace_back function is used to insert new element at the end of the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  
  //insert a new element at the end of the vector
  MyVector.emplace_back(1000);

  //insert a another new element at the end of the vector
  MyVector.emplace_back(2000);

  //insert a another new element at the end of the vector
  MyVector.emplace_back(3000);

  cout<<"MyVector contains: ";
  for(int i=0; i< MyVector.size(); i++)
    cout<<MyVector[i]<<" ";   

  return 0;
}

The output of the above code will be:

MyVector contains: 10 20 30 40 50 1000 2000 3000  

❮ C++ <vector> Library