stack push() and pop() in C++ STL

C++Server Side ProgrammingProgramming

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

What is Stack in C++ STL?

Stacks are the data structure which 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::push()?

stack::push() function is an inbuilt function in C++ STL, which is defined in <stack>header file. push() is used to push or insert an element at the top of the stack container. The content of the new element is copied and initialized.

Syntax

stack_name.push(value_type& val);

Parameters

The function accepts the following parameter(s) −

  • val − Value which we want to push

Return value

This function returns nothing

Input 

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

Output 

3 2 1

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int>stck;
   int Product = 1;
   stck.push(1);
   stck.push(2);
   stck.push(3);
   stck.push(4);
   stck.push(5);
   stck.push(6);
   while (!stck.empty()){
      Product = Product * stck.top();
      cout<<"\nsize of stack is: "<<stck.size();
      stck.pop();
   }
   return 0;
}

Output

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

size of stack is: 6
size of stack is: 5
size of stack is: 4
size of stack is: 3
size of stack is: 2
size of stack is: 1

What is stack::pop()?

stack::pop() function is an inbuilt function in C++ STL, which is defined in <stack>header file. pop() is used to pop or remove an element from the top of the stack container. The content from the top is removed and the size of the container is reduced by 1.

Syntax

stack_name.pop();

Parameters

The function accepts no parameter(s) −

Return value

This function returns nothing

Input 

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

Output 

2 1

Example

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
int main(){
   stack<int> stck;
   int Product = 1;
   stck.push(1);
   stck.push(2);
   stck.push(3);
   stck.push(4);
   stck.push(5);
   stck.push(6);
   while (!stck.empty()){
      Product = Product * stck.top();
      cout<<"\nsize of stack is: "<<stck.size();
      stck.pop();
   }
   return 0;
}

Output

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

size of stack is: 6
size of stack is: 5
size of stack is: 4
size of stack is: 3
size of stack is: 2
size of stack is: 1
raja
Published on 22-Apr-2020 12:21:00
Advertisements