Implement Vector as a Stack in C++

In this tutorial,  we will learn how to Implement Vector as a stack in C++. Let us begin the tutorial with some basic knowledge.

What is a Vector in C++?

Vectors are just like arrays but there is a slight difference between them i.e. vectors are dynamic.

Header file used is:

#include <vector>

What is a Stack?

Stacks are operated on the Last In First Out (LIFO) basis i.e. the element added last will be deleted first from the list. We perform Insertion and deletion in a stack. For Insertion, we use the term push and for Deletion we use the term pop.

Header file used is:

#include <stack>

Push Function

To add the element in the stack we use the push operation.

Also read: push_back() and pop_back() function in C++ STL

Syntax is:

stack_name.push(element);

Pop Function

To delete the element from the stack we use the pop operation. It deletes the element from the top.

Syntax is:

stack_name.pop();

Implement vector as a stack in C++

Now let us write the code to illustrate the same.

#include <iostream>
#include <vector>
#include <stack>

using namespace std;
int main() 
{
  stack< int, vector<int> > stckk; 
  stckk.push(2);
  stckk.push(21);
  stckk.push(45);
  stckk.push(76);
  cout <<"Top Element is "<<stckk.top() << endl;
  
  while(!stckk.empty())
   { stckk.pop();
     if(stckk.empty())
     cout << "The Stack is now Empty." << endl;
   } 
  return 0;
}

Output:

Top Element is 76 
The Stack is now Empty.

Explanation:

In this code, first of all,  Stack is stored in a vector then we will push the elements which will be stored in the stack. Then we print the top element of the stack, after that we will pop the elements from the stack until the stack is empty.

I hope that this will help you to solve your problem.

Leave a Reply

Your email address will not be published. Required fields are marked *