Sat. Oct 1st, 2022

Hello Android

All android in one place

Stack Class Implementation In C++ [Easy]

3 min read

Today we will learn about stack class implementation in C++. We will start learning about stacks from the scratch. Today we will cover the following points.

  • What is a stack?
  • Some basic properties of a stack
  • Structure of a stack class
  • Stack class code using C++

What Is A Stack?

A stack is simply a data structure that follows the LIFO property. Wait, what is a LIFO property? LIFO stands for Last In First Out. This means that the last element that is pushed into the stack is the first to be popped.

Still didn’t get it? No worries below are some real-life examples for you.

  • Pile of books
  • Forward and backward functions in a browser
  • Undo functionality in applications
  • Recursive function calls
  • Backtracking algorithms

Basic Features Of A Stack

A stack primarily is a vector that doesn’t allow random access. Instead, it only allows insertion and deletion at the end. There can be different types of stacks like a min-stack, a max-stack, or a normal stack. The min and the max stacks keep track of the min and the maximum elements so far respectively. The stacks only give access to the top-most(last) element of the stack(vector).

Writing A Stack Class in C++

Our prime objective for today’s article is to implement a template stack class in C++. Let’s discuss the data members and member functions of a stack class. The advantage of using a template stack class is that the stack implementation of custom data types is allowed.

Data Members

The structure of a stack is really simple, it just consists of a vector. This vector is declared as a private data member to prevent random access to the elements.

vector <T> v; #here T represents any generic data type for our template class

Member Functions

Some of the functions available to use with the stack data structures are given below.

  • void push(T data): Inserts data at the top position of the stack
  • void pop(): Deletes the last element of the stack
  • T top(): Returns the top-most element of the stack
  • int size(): Returns the current size of the stack
  • bool is_empty(): It returns a boolean value, true if the stack is empty otherwise false.

push()

        void push(T data)
        {
                v.push_back(data); //simply insert the data into the stack
        }

pop()

        void pop()
        {
                if(!this->is_empty()) // first we check if the stack is not already empty
                        v.pop_back();
        }

is_empty()

        bool is_empty() const
        {
                return size(v) == 0; // size() function belongs to the std namespace
        }

top()

        T top() const
        {
                // this function is declared as const because it
               // doesn't change any data members of the class
                return v[size(v) - 1];
        }

Stack Class Implementation In C++

Below is a very simple and easy to understand C++ program code that explains some of the basic features of a stack

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class Stack
{
	vector <T> v;
public:
	void push(T data)
	{
		v.push_back(data);
	}

	bool is_empty() const
	{
		return v.size() == 0;
	}

	void pop()
	{
		if(!this->is_empty())
			v.pop_back();
	}

	T top() const
	{
		return v[v.size() - 1];
	}
};

template <typename T>
void print_stack(Stack <T> s)
{
	// note that the stack is not passed by reference,
	// hence any change that that occurs in the stack is
	// not reflected back outside this function call

	cout << "The stack is:" << endl;
	cout << "Top --> ";
	while(!s.is_empty())
	{
		cout << s.top() << " --> ";
		s.pop();
	}
	cout << "Bottom" << endl;
}

int main()
{
	Stack <string> friends;
	
	cout << "Enter the names of your friends, type |done| to stop" << endl;

	while(true)
	{
		string s;
		cin >> s;

		if(s == "done")
			break;
		friends.push(s);
	}

	print_stack(friends);

	cout << "Let's see how deletion works in stacks" << endl;

	while(!friends.is_empty())
	{
		cout << "Deleting: " << friends.top() << endl;
		friends.pop();
		print_stack(friends);
	}

	return 0;
}
Stack Program Code
Stack Program Code 2
Main Function Code

Output

Stack Program Output
Stack Program Output

Conclusion

Okay so let’s wrap up today’s article by recalling what have we just learned. First, we understood the most important property of a stack i.e. LIFO property, and read looked at some real-life uses of stacks. Secondly, we discussed the basic features and functions of a template stack class. In the end, we implemented a C++ program that demonstrates the functioning of stacks. That’s it for today, thanks for reading.

References

To learn more about vectors and stacks you can refer to the following websites.

https://www.journaldev.com/56360/vector-class-in-cpp

https://en.cppreference.com/w/cpp/container/stack

www.hello-android.com

Leave a Reply

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

Hello android © All rights reserved. | Newsphere by AF themes.