Signup/Sign In

STACK Container in C++ STL

The stack container is used to replicate stacks in c++, insertion and deletion is always performed at the top of the stack.

To know more about the Stack data Structure, visit: STACK Data Structure

Here is the syntax of defining a stack in stl :

stack<object_type> stack_name;

The above statement will create a stack named stack_name of type object_type.


Member Functions of Stack Container

Following are some of the most commonly used functions of Stack container in STL:


push function

push() is used to insert the element in the stack, the elements are inserted at the top of the stack.

Push method of Stacks

#include <iostream>      
#include <stack>

using namespace std;   
     
int main ()
{
    stack<int> s;   // creates an empty stack of integer s 
    
    s.push(2);   // pushes 2 in the stack  , now top =2
    s.push(3);   // pushes 3 in the stack  , now top =3

}

pop function

This method is used to removes single element from the stack. It reduces the size of the stack by 1. The element removed is always the topmost element of the stack (most recently added element) . The pop() method does not return anything.

Pop method of Stacks


top function

This method returns the topmost element of the stack. Note that this method returns the element, not removes it, unlike pop().

SYNTAX: top()


size and empty functions

size() returns the number of elements present in the stack, whereas empty() checks if the stack is empty or not. empty returns true if the stack is empty else false is returned.


swap function

This method swaps the elements of the two stacks.

#include <iostream>      
#include <stack>

using namespace std;  
      
int main ()
{
    stack<int> s; 
    
    // pushing elements into stack
    s.push(2);   
    s.push(3);   
    s.push(4);   
    
    cout << s.top();   // prints 4, as 4 is the topmost element 
    
    cout << s.size();  // prints 3, as there are 3 elements in 
}