Open In App

Implement a Stack Using Vectors in C++

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

A stack is a data structure that follows the LIFO (Last In First Out) property means the element that is inserted at last will come out first whereas vectors are dynamic arrays. In this article, we will learn how to implement a stack using vectors in C++.

Implementing a Stack Using Vectors in C++

Vectors offer dynamic resizing capabilities, allowing the std::stack to grow or shrink as needed. Moreover, the std::vector allows the insertion and deletion at the end in O(1) time complexity.

The stack has the following basic operations which we will implement these operations in our program:

  • push(): Adds an element to the top of the stack.
  • pop(): Removes and returns the top element.
  • top(): Returns the top element without removing it.
  • isEmpty(): Checks if the stack is empty.

C++ Program to Implement Stack Using Vector

The below example demonstrates how we can implement stack using vectors in C++.


Output
Pushed: 10
Pushed: 20
Pushed: 30
Pushed: 40

Popped: 40

Top element: 30

All the set operations that are provided here will be able to be executed in O(1) time.




Next Article
Practice Tags :

Similar Reads