Open In App

Implement a Stack Using Vectors in C++

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
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++.

C++




// C++ program to implement stack using vector
#include <iostream>
#include <vector>
  
using namespace std;
  
class Stack {
  
private:
    // The vector to store stack elements
    vector<int> v;
  
public:
    // Function to push an element onto the stack
    void push(int data)
    {
        v.push_back(data);
        cout << "Pushed: " << data << endl;
    }
  
    // Function to pop an element from the stack
    int pop()
    {
        if (isEmpty()) {
            cout << "Stack is empty. Cannot pop.\n";
            return -1;
        }
        int top = v.back();
        v.pop_back();
        cout << "\nPopped: " << top << endl;
        return top;
    }
  
    // Function to get the top element of the stack without
    // removing it
    int top()
    {
        if (isEmpty()) {
            cout << "Stack is empty. No top element.\n";
            return -1;
        }
        return v.back();
    }
  
    // Function to check if the stack is empty
    bool isEmpty() { return v.empty(); }
};
  
int main()
{
    Stack myStack;
  
    // Push elements onto the stack
    myStack.push(10);
    myStack.push(20);
    myStack.push(30);
    myStack.push(40);
  
    // Pop an element from the stack and print it
    myStack.pop();
  
    // Get the top element of the stack and print it
    int topElement = myStack.top();
    if (topElement != -1) {
        cout << "\nTop element: " << topElement << endl;
    }
  
    return 0;
}


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads