Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ stack::emplace function is used to insert new element at the top of the stack, after its currently added element. Each insertion of element increases the stack container size by one.

Syntax

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

Parameters

args Arguments forwarded to construct the new element.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the stack::emplace function is used to insert new element at the top of the stack MyStack.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> MyStack;
  
  //add new elements in the stack using emplace function
  MyStack.emplace(10);
  MyStack.emplace(20);
  MyStack.emplace(30);
  MyStack.emplace(40);
  MyStack.emplace(50);

  cout<<"MyStack contains: ";
  while(!MyStack.empty()) {
   cout<<MyStack.top()<<" "; 
   MyStack.pop();  
  }
  return 0;
}

The output of the above code will be:

MyStack contains: 50 40 30 20 10 

❮ C++ - Stack