stack emplace() in C++ STL


In this article we will be discussing the working, syntax, and examples of stack::emplace() function in C++ STL.

What is Stack in C++ STL?

Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top.

What is stack::emplace()?

stack::emplace() function is an inbuilt function in C++ STL, which is defined in <stack>header file. emplace() is used to construct and insert an element in the stack container associated with the function.

When we run this function, the function inserts a new element on the top of the stack and makes the new inserted element as the top element. This function calls the emplace_back to insert the new element at the top.

Syntax

stack_name.emplace(Args& args);

Parameters

The function accepts the following parameter(s) −

  • args − These are the arguments we want to emplace.

Return value

This function returns nothing.

Input 

std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);

Output 

3 2 1

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   stck.emplace(10);
   stck.emplace(20);
   stck.emplace(30);
   stck.emplace(40);
   stck.emplace(50);
   stck.emplace(60);
   cout << "Elements in stack are: ";
   while (!stck.empty()){
      cout<<stck.top() << " ";
      stck.pop();
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Elements in stack are: 60 50 40 30 20 10

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   int total = 0;
   stck.emplace(10);
   stck.emplace(20);
   stck.emplace(30);
   stck.emplace(40);
   stck.emplace(50);
   stck.emplace(60);
   cout << "Elements in stack are: ";
   while (!stck.empty()){
      cout<<stck.top() << " ";
      stck.pop();
      total++;
   }
   cout<<"\nTotal number of elements in stack are: "<<total;
   return 0;
}

Output

If we run the above code it will generate the following output −

Elements in stack are: 60 50 40 30 20 10
Total number of elements in stack are: 6

Updated on: 22-Apr-2020

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements