Implement a Stack Using Vectors in C++
Last Updated :
15 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
class Stack {
private :
vector< int > v;
public :
void push( int data)
{
v.push_back(data);
cout << "Pushed: " << data << endl;
}
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;
}
int top()
{
if (isEmpty()) {
cout << "Stack is empty. No top element.\n" ;
return -1;
}
return v.back();
}
bool isEmpty() { return v.empty(); }
};
int main()
{
Stack myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.push(40);
myStack.pop();
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.
Share your thoughts in the comments
Please Login to comment...