Implementing Stack Using Class Templates in C++
Last Updated :
02 Feb, 2022
The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by the keyword ‘class’.
Illustration:
Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order.
Example:
C++14
// C++ Program to Implement stack using Class Templates
// Including input output libraries
#include <iostream>
// Header File including all string functions
#include <string>
using namespace std;
// Taking size of stack as 10
#define SIZE 5
// Class
// To represent stack using template by class
// taking class in template
template <class T> class Stack {
// Public access modifier
public:
// Empty constructor
Stack();
// Method 1
// To add element to stack which can be any type
// using stack push() operation
void push(T k);
// Method 2
// To remove top element from stack
// using pop() operation
T pop();
// Method 3
// To print top element in stack
// using peek() method
T topElement();
// Method 4
// To check whether stack is full
// using isFull() method
bool isFull();
// Method 5
// To check whether stack is empty
// using isEmpty() method
bool isEmpty();
private:
// Taking data member top
int top;
// Initialising stack(array) of given size
T st[SIZE];
};
// Method 6
// To initialise top to
// -1(default constructor)
template <class T> Stack<T>::Stack() { top = -1; }
// Method 7
// To add element element k to stack
template <class T> void Stack<T>::push(T k)
{
// Checking whether stack is completely filled
if (isFull()) {
// Display message when no elements can be pushed
// into it
cout << "Stack is full\n";
}
// Inserted element
cout << "Inserted element " << k << endl;
// Incrementing the top by unity as element
// is to be inserted
top = top + 1;
// Now, adding element to stack
st[top] = k;
}
// Method 8
// To check if the stack is empty
template <class T> bool Stack<T>::isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
// Utility methods
// Method 9
// To check if the stack is full or not
template <class T> bool Stack<T>::isFull()
{
// Till top in inside the stack
if (top == (SIZE - 1))
return 1;
else
// As top can not exceeds th size
return 0;
}
// Method 10
template <class T> T Stack<T>::pop()
{
// Initialising a variable to store popped element
T popped_element = st[top];
// Decreasing the top as
// element is getting out from the stack
top--;
// Returning the element/s that is/are popped
return popped_element;
}
// Method 11
template <class T> T Stack<T>::topElement()
{
// Initialising a variable to store top element
T top_element = st[top];
// Returning the top element
return top_element;
}
// Method 12
// Main driver method
int main()
{
// Creating object of Stack class in main() method
// Declaring objects of type Integer and String
Stack<int> integer_stack;
Stack<string> string_stack;
// Adding elements to integer stack object
// Custom integer entries
integer_stack.push(2);
integer_stack.push(54);
integer_stack.push(255);
// Adding elements to string stack
// Custom string entries
string_stack.push("Welcome");
string_stack.push("to");
string_stack.push("GeeksforGeeks");
// Now, removing element from integer stack
cout << integer_stack.pop() << " is removed from stack"
<< endl;
// Removing top element from string stack
cout << string_stack.pop() << " is removed from stack "
<< endl;
// Print and display the top element in integer stack
cout << "Top element is " << integer_stack.topElement()
<< endl;
// Print and display the top element in string stack
cout << "Top element is " << string_stack.topElement()
<< endl;
return 0;
}
OutputInserted element 2
Inserted element 54
Inserted element 255
Inserted element Welcome
Inserted element to
Inserted element GeeksforGeeks
255 is removed from stack
GeeksforGeeks is removed from stack
Top element is 54
Top element is to
Output explanation:
Here two data types (integer and string) are implemented using a single stack class. First, two objects are taken one is for integer class and the second is for the string class, Elements are inserted in both the classes using push() and isFull() method of stack class. Elements are removed using pop and isEmpty() functions of stack class. Finally, the top element is printed for each class using the top element() function.
Similar Reads
Stack in C++ STL In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally
5 min read
stack empty() and stack size() in C++ STL The std::stack::size() and std::stack::empty() in C++ are built-in functions that are used to provide information about the size of the stack. They are the member functions of the std::stack container defined inside <stack> header file.stack::empty()The stack::empty() method is used to check w
2 min read
stack::push() and stack::pop() in C++ STL The stack::push() and stack::pop() method in stack container is used to insert and delete the element from the top of stack. They are the member functions of std::stack container defined inside <stack> header file. In this article, we will learn how to use stack::push() and stack::pop() method
2 min read
stack top() in C++ STL In C++, the std::stack::top() is used to find the top element of the std::stack container. It is a member function of std::stack class defined inside the <stack> header file. In this article, we will learn how to find the top element of stack using stack::top() in C++.Example:C++#include <b
2 min read
stack emplace() in C++ STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. stack::emplace() This function is used to insert a new element into the stack container, the new element is added on top o
3 min read
stack swap() in C++ STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only.stack::swap()This function is used to swap the contents of one stack with another stack of same type but the size may vary. Sy
2 min read
List of Stacks in C++ STL Prerequisite: List, Stack Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Syntax: list <Type> name_of_list; Stack are a type of container adaptor wit
3 min read
Implementing Stack Using Class Templates in C++ The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or
5 min read
How to implement a Stack using list in C++ STL In this article, we will discuss how to implement a Stack using list in C++ STL. Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:1. Push: Push an element into the stack.2. Pop: Removes the element by following
3 min read
Queue using Stacks Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.Table of ContentBy Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Making
11 min read