C++ Standard Library C++ STL Library

C++ <stack> - pop() Function



The C++ stack::pop function is used to delete the top element of the stack. In a stack, addition and deletion of a element occurs from the top of the stack. Hence, The most recently added element will be the top element of the stack. Every deletion of element results into reducing the container size by one unless the stack is empty.

Syntax

void pop();
void pop();

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the stack::pop function is used to delete top elements of the stack called MyStack.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> MyStack;

  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);
  MyStack.push(40);
  MyStack.push(50);

  cout<<"The top element of the stack is: "<<MyStack.top();
  //deletes top element of the stack
  MyStack.pop();

  cout<<"\nNow, the top element of the stack is: "<<MyStack.top();
  //deletes next top element of the stack
  MyStack.pop();

  cout<<"\nNow, the top element of the stack is: "<<MyStack.top();
  return 0;
}

The output of the above code will be:

The top element of the stack is: 50
Now, the top element of the stack is: 40
Now, the top element of the stack is: 30

❮ C++ <stack> Library

5