Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Stacks in C++
3.
Stacks in C++ using STL
4.
Essential methods of STL's stack in C++
4.1.
push()
4.1.1.
Input 
4.1.2.
Output 
4.1.3.
Input 
4.1.4.
Output
4.2.
pop() 
4.2.1.
Input 
4.2.2.
Output
4.2.3.
Input
4.2.4.
Output 
4.3.
empty()
4.3.1.
Input
4.3.2.
Output 
4.4.
size()
4.4.1.
Input 
4.4.2.
Output
4.4.3.
 
4.5.
top()
4.5.1.
Input 
4.5.2.
Output 
5.
Implementation of Stack in C++ using STL
5.1.
Output
5.2.
Explanation
6.
Complexity Analysis
7.
Frequently Asked Questions
8.
Conclusion
Last Updated: Sep 25, 2024

Stack in C++

Introduction

Stacks are container adapters designed to function in a LIFO (last-in, first-out) environment, where components are only added and deleted from one end of the container.

Stacks are implemented using container adaptors, classes that use an encapsulated object of a specific container class as its underlying container and give a defined set of member methods to access the components. The top of the stack, often known as the "back" of the given container, is where elements are pushed or popped.

We will help you understand stacks in C++’s STL and what are some essential methods available in STL for stack containers with examples.

Stacks in C++

A stack in C++ may be conveniently constructed using an array or a linked list. And each of them provides us with a set of functions that we can use to retrieve the items we're interested in.

If you're curious, here's how to do it in code. Don't worry; Coding Ninjas will take care of everything.
 

Because of the language's and libraries' extensive capabilities, Standard Template Library (STL) is a helpful tool that may save you time in coding contests. The nice thing is that STL also assists with stack implementation in C++. The STL will be used to implement a stack in C++ in today's article.

To learn more about C++ STL, visit the C++ guided path.

Stacks in C++ using STL

For implementing stack data structures, C++ offers an STL. To use a stack or perform any operations on a stack in C++, the header file "#include <stack>" must be included first. The stack is then defined using the syntax below.

std::stack<T> stack_one;
// or
std::stack<T, container> stack_one (container_instance);
You can also try this code with Online C++ Compiler
Run Code

Where:

  • T is the data type of elements in the stack like int, float.
  • The data structure used to initialize your stack is called a container. This is optional, and the stack's underlying container is an enclosed object of vector or deque (by default) or list (sequential container class), with a specified set of member functions for accessing its contents.
  • <container_instance> is the instance of container type
     

This may look difficult, but don't worry! Following that, we'll go through all of the operations that can be performed on a stack in STL and the code that goes with them.

Essential methods of STL's stack in C++

We will now discuss some of the most commonly used STL methods for a stack in C++.

push()

We either add or delete elements when we use a container. We may push components into our stack using the push technique. And when we add a new element to our stack, it is always added to the top.

The syntax to the function is 

<stack_name>.push()
You can also try this code with Online C++ Compiler
Run Code

Input 

stack_one.push(4);
stack_one.push(12);
You can also try this code with Online C++ Compiler
Run Code

Output 

4 12

Source
 

Input 

stack_one.push(15);
You can also try this code with Online C++ Compiler
Run Code

Output

4 12 15

Source
 

Parameters: The element value that needs to be added is passed.

Return Value:  void

pop() 

We either add or delete elements when we use a container. We may pop components from our stack using the pop technique. The top element is permanently eliminated when we pop an element from our stack.
 

The syntax of the function is

<stack_name>.pop()
You can also try this code with Online C++ Compiler
Run Code

Input 

stack_one = 10, 8, 12, 4

stack_one.pop();
You can also try this code with Online C++ Compiler
Run Code

Output

4 12 8

Source

Input

stack_one.pop();
You can also try this code with Online C++ Compiler
Run Code

Output 

4 12

Source

 

Parameters:  No parameter is passed

Return Value:  void

empty()

Since stacks are containers, they can be loaded with items or left empty. To obtain the same, use the empty() method.

The syntax of the empty function is 

<stack_name>.empty()
You can also try this code with Online C++ Compiler
Run Code

 

Input

stack_one = 4, 12

stack_one.empty();
You can also try this code with Online C++ Compiler
Run Code

Output 

False

Source

 

Parameters: No parameters are passed.

Return Value: Returns true if our stack is empty and false if our stack is not empty.

size()

The size is another action or function we may do on a stack. The size of our stack or the number of elements in our container is returned by this method.

The syntax to the function size() is

<stack_name>.size()
You can also try this code with Online C++ Compiler
Run Code

 

Input 

stack_one = 4, 12, 8

stack_one.size();
You can also try this code with Online C++ Compiler
Run Code

Output

3

Source

 

Parameters: No parameters are passed.

Return Value: Number of elements in the stack

top()

The top element, i.e., the newest element, always stays on top of the stack since the stack follows the last in first out sequence of items. This top() method returns that element(newly inserted).

The syntax to the top function comes as follows.

<stack_name>.top()
You can also try this code with Online C++ Compiler
Run Code

 

Input 

stack_one.push(4);
stack_one.push(12);
stack_one.push(8);
stack_one.push(10);
stack_one.top();
You can also try this code with Online C++ Compiler
Run Code

Output 

10

Source

Implementation of Stack in C++ using STL

Let us implement all the functions discussed above, i.e., push(), pop(), empty(), top(), and size(), simultaneously in the below program.


Code

// C++ program to implement
#include <iostream>
#include <stack>
using namespace std;

int main()
{
    stack<int> stack_one;
    stack_one.push(2);
    stack_one.push(3);
    stack_one.push(4);
    stack_one.push(5);
    // Stack becomes 2, 3, 4, 5

    stack_one.pop();
    stack_one.pop();
    // Stack becomes 2, 3

    if(stack_one.empty()){
        cout << "The stack is empty"<<endl;
        // Stack_one isn't empty so we'll get to else part
    }
    else{
        cout << "The stack is not empty" << endl;
    }

    cout << stack_one.top() << endl;
    // We have 3 as output as 3 is on the top

    cout << stack_one.size() << endl;
    // We will get 2 as the output as we have 2 and 3 in the stack
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

The stack is not empty
3  
2    

Explanation

Let's see how the above code works!

 We use the usual header files, and an extra header file #include <stack>.

  • We can now store integer values in the container since we've created an integer stack.
  • We use the push() function to add elements in the stack -
    • Add 2 to the stack
    • Add 3 to the stack
    • Add 4 to the stack
    • Add 5 to the stack. 
  • Pop() one element from the stack. '5' gets removed from the stack.
  • Pop one more element from the stack. '4' gets removed from the stack.
  • We use empty() to determine whether or not the stack is empty (we get to the else part because our stack is not empty).
  • We use the top() method to get the top-most item in our stack. (The number 3 is our top-most element.)
  • We use size() to determine the size of the remaining stack. We get '2' as the output since our stack has only '2' elements, i.e., '2' and '3'.
  • End of the main function.

Complexity Analysis

The functions associated with stack are: 

Function

Use

Time Complexity

empty()Returns true if our stack is empty; otherwise, falseO(1) 
size()Returns the size of the stackO(1)
top()Returns a reference to the top-most element of the stackO(1)
push(value)Adds the element 'value' at the top of the stackO(1)
pop()Deletes the top-most element of the stack and returns nothing.O(1) 

Frequently Asked Questions

  1. What is STL in C++?
    STL - Standard Template Library is a software library containing pre-written instructions for commonly used data structures such as stacks, maps, sets, searching, sorting, etc.
     
  2. What is an example of a stack in real life?
    We use the concept of LIFO/stack in our daily activities such as in a cafeteria, a stack of trays; In a cabinet, a stack of plates; In a classroom; a stack of books.
     
  3. What are some applications of stacks?
    Some of the applications of Stacks are

a. Expression Evaluation

b. Expression Conversion

    i. Infix to Postfix

    ii. Infix to Prefix

    iii. Postfix to Infix

    iv. Prefix to Infix

c. Backtracking

d. Memory Management

Conclusion

This article extensively discusses stacks and how to implement stacks in C++ using STL. The examples were very thorough in representing the working of a stack in C++.

We hope that this blog has helped you enhance your knowledge of stacks and their implementation in C++.  You can also consider our Mern Stack Course to give your career an edge over others.

 

Happy Coding!

Live masterclass