C++ – Implement Stack with vector
Vector is an array with homogenous elements. Stack is a data structure which enters the data in LIFO manner (last in, first out). It means that the element entered last into the stack will be removed first. Here we make use of a vector to implement the stack.
A vector is a Sequence that supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle.
Thus we can insert an element in the vector in the end at O(1) time and similarly remove the element from the end in O(1) time
We are also making a generic stack so that it can be used by different data types. Here we demonstrate using integer and floating point values
#include <vector>
#include <iostream>
using namespace std;
/*Using template to make a generic stack class*/
template <typename T> class Stack {
private:
/*Data elements of the Stack*/
vector <T> data;
public:
/*Entering the element into the stack*/
void push (T element) {
data.push_back(element);
}
/*Returning the last entered element from the stack after removing it*/
T pop() {
T element = data.back(); /*Accessing the last element*/
data.pop_back(); /*Removing the last element*/
return element; /*Returning the element*/
}
/*Returns whether the stack is empty or not*/
bool empty(){
return data.empty();
}
/*Printing the value of the template data*/
static void print_value(T value) {
cout << value;
}
};
int main() {
/*Creating a stack for integers*/
Stack<int> stack;
int i;
for (i=0;i<25;i++) {
cout << "Pushing " << i <<"\n";
stack.push(i);
}
cout <<"Popped out elements:\n";
while(!stack.empty()) {
Stack<int>::print_value(stack.pop());
cout <<"\n";
}
/*Creating a stack for floating point*/
Stack<float> fstack;
for (i=0;i<25;i++) {
cout << "Pushing " << i*2.3 <<"\n";
fstack.push(i*2.3);
}
cout <<"Popped out elements:\n";
while(!fstack.empty()) {
Stack<float>::print_value(fstack.pop());
cout <<"\n";
}
}
The output of the program is something like this
Pushing 0 Pushing 1 Pushing 2 Pushing 3 Pushing 4 Pushing 5 Pushing 6 Pushing 7 Pushing 8 Pushing 9 Pushing 10 Pushing 11 Pushing 12 Pushing 13 Pushing 14 Pushing 15 Pushing 16 Pushing 17 Pushing 18 Pushing 19 Pushing 20 Pushing 21 Pushing 22 Pushing 23 Pushing 24 Popped out elements: 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Pushing 0 Pushing 2.3 Pushing 4.6 Pushing 6.9 Pushing 9.2 Pushing 11.5 Pushing 13.8 Pushing 16.1 Pushing 18.4 Pushing 20.7 Pushing 23 Pushing 25.3 Pushing 27.6 Pushing 29.9 Pushing 32.2 Pushing 34.5 Pushing 36.8 Pushing 39.1 Pushing 41.4 Pushing 43.7 Pushing 46 Pushing 48.3 Pushing 50.6 Pushing 52.9 Pushing 55.2 Popped out elements: 55.2 52.9 50.6 48.3 46 43.7 41.4 39.1 36.8 34.5 32.2 29.9 27.6 25.3 23 20.7 18.4 16.1 13.8 11.5 9.2 6.9 4.6 2.3 0
Comments: