The Wayback Machine - https://web.archive.org/web/20240828183347/https://www.geeksforgeeks.org/implementing-stack-using-class-templates-in-cpp/
Open In App

Implementing Stack Using Class Templates in C++

Last Updated : 02 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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;
}


Output

Inserted 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.

 



Previous Article
Next Article

Similar Reads

Implementing Stack in C#
Stack is a linear data structure. It follows LIFO(Last In First Out) pattern for Input/output. Following three basic operations are performed in the stack: Push: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow condition. Pop: Removes an item from the stack. The items are popped in the reversed order in which
2 min read
Implement dynamic deque using templates class and a circular array
The task is to implement a dynamic Deque using templates class and a circular array, having the following functionalities: front(): Get the front item from the deque.back(): Get the last item from the deque.push_back(X): Push X at the end of the deque.push_front(X): Push X at the start of the deque.pop_front(): Delete an element from the start of t
9 min read
Implement dynamic queue using templates class and a circular array
In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality: Front(): Get the front item from the queue.Back(): Get the last item from the queue.Push(X): Push the X in the queue at the end of the queue.Pop(): Delete an element from the queue. Below is the step-by-step illustratio
7 min read
Sort a stack using a temporary stack
Given a stack of integers, sort it in ascending order using another temporary stack. Examples: Input : [34, 3, 31, 98, 92, 23] Output : [3, 23, 31, 34, 92, 98] Input : [3, 5, 1, 4, 2, 8] Output : [1, 2, 3, 4, 5, 8] Recommended PracticeSort a stackTry It! Algorithm: Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an
6 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –&gt; TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
stack empty() and stack size() 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 and (top) an element is removed from that end only. stack::empty()empty() function is used to check if the stack container is empty or not. Syntax : stackname.empty()Parameters :No parameters are passed.Returns :True, if sta
3 min read
Stack Permutations (Check if an array is stack permutation of other)
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from the input queue to the output queue with the help of a stack and the built-in push and pop functions. The rules are: Only dequeue from the input queue.Use inbuilt push, and pop functions in the single stack.Stack and input queue must
15+ min read
Reversing a Stack with the help of another empty Stack
Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach 1: Follow the steps below to solve the problem: Initialize an empty stack.Po
8 min read
Implementing Water Supply Problem using Breadth First Search
Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through
10 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Implementing Rich getting Richer phenomenon using Barabasi Albert Model in Python
Prerequisite- Introduction to Social Networks, Barabasi Albert Graph In social networks, there is a phenomenon called Rich getting Richer also known as Preferential Attachment. In Preferential Attachment, a person who is already rich gets more and more and a person who is having less gets less. This is called the Rich getting Richer phenomena or Pr
4 min read
C++ | Templates | Question 1
Which of the following is true about templates. 1) Template is a feature of C++ that allows us to write one code for different data types. 2) We can write one function that can be used for all data types including user defined types. Like sort(), max(), min(), ..etc. 3) We can write one class or struct that can be used for all data types including
1 min read
C++ | Templates | Question 2
Predict the output? #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fun(const T&amp;x) { static int count = 0; cout &lt;&lt; &quot;x = &quot; &lt;&lt; x &lt;&lt; &quot; count = &quot; &lt;&lt; count &lt;&lt; endl; ++count; return; } int main() { fun&lt;int&gt; (1); cout &lt;&lt; endl; fun&lt;int&gt;(1); cout &lt;&lt;
1 min read
C++ | Templates | Question 3
#include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T max(T x, T y) { return (x &gt; y)? x : y; } int main() { cout &lt;&lt; max(3, 7) &lt;&lt; std::endl; cout &lt;&lt; max(3.0, 7.0) &lt;&lt; std::endl; cout &lt;&lt; max(3, 7.0) &lt;&lt; std::endl; return 0; } (A) 7 7.0 7.0 (B) Compiler Error in all cout statements as data ty
1 min read
C++ | Templates | Question 4
Output of following program? #include &lt;iostream&gt; using namespace std; template &lt;class T&gt; class Test { private: T val; public: static int count; Test() { count++; } }; template&lt;class T&gt; int Test&lt;T&gt;::count = 0; int main() { Test&lt;int&gt; a; Test&lt;int&gt; b; Test&lt;double&gt; c; cout &lt;&lt; Test&lt;int&gt;::count &lt;
1 min read
C++ | Templates | Question 5
Output of following program? Assume that the size of char is 1 byte and size of int is 4 bytes, and there is no alignment done by the compiler. #include&lt;iostream&gt; #include&lt;stdlib.h&gt; using namespace std; template&lt;class T, class U&gt; class A { T x; U y; static int count; }; int main() { A&lt;char, char&gt; a; A&lt;int, int&gt; b; cout
1 min read
C++ | Templates | Question 6
Output of following program? Assume that the size of int is 4 bytes and size of double is 8 bytes, and there is no alignment done by the compiler. #include&lt;iostream&gt; #include&lt;stdlib.h&gt; using namespace std; template&lt;class T, class U, class V=double&gt; class A { T x; U y; V z; static int count; }; int main() { A&lt;int, int&gt; a; A
1 min read
C++ | Templates | Question 10
Output of following program. #include &lt;iostream&gt; using namespace std; template &lt;class T, int max&gt; int arrMin(T arr[], int n) { int m = max; for (int i = 0; i &lt; n; i++) if (arr[i] &lt; m) m = arr[i]; return m; } int main() { int arr1[] = {10, 20, 15, 12}; int n1 = sizeof(arr1)/sizeof(arr1[0]); char arr2[] = {1, 2, 3}; int n2 = sizeof(
2 min read
C++ | Templates | Question 8
Output? #include &lt;iostream&gt; using namespace std; template &lt;int i&gt; void fun() { i = 20; cout &lt;&lt; i; } int main() { fun&lt;10&gt;(); return 0; } (A) 10 (B) 20 (C) Compiler Error Answer: (C) Explanation: Compiler error in line "i = 20;" Non-type parameters must be const, so they cannot be modified.Quiz of this Question
1 min read
C++ | Templates | Question 9
Output? #include &lt;iostream&gt; using namespace std; template &lt;class T&gt; T max (T &amp;a, T &amp;b) { return (a &gt; b)? a : b; } template &lt;&gt; int max &lt;int&gt; (int &amp;a, int &amp;b) { cout &lt;&lt; &quot;Called &quot;; return (a &gt; b)? a : b; } int main () { int a = 10, b = 20; cout &lt;&lt; max &lt;int&gt; (a, b); } (A) 20 (B)
1 min read
C++ | Templates | Question 10
Output? #include &lt;iostream&gt; using namespace std; template&lt;int n&gt; struct funStruct { static const int val = 2*funStruct&lt;n-1&gt;::val; }; template&lt;&gt; struct funStruct&lt;0&gt; { static const int val = 1 ; }; int main() { cout &lt;&lt; funStruct&lt;10&gt;::val &lt;&lt; endl; return 0; } (A) Compiler Error (B) 1024 (C) 2 (D) 1 Answe
1 min read
not1 and not2 function templates in C++ STL with Examples
These are functions which takes unary and binary function object(functors) and returns complement of that function objects. It can be usable in competitive programming to get complement of binary and unary functions. These functions are very useful when writing code for complement function is harder or lengthy. For example, if we want to delete con
3 min read
Abbreviated Function Templates in C++ 20
Abbreviated Function Template is a new feature introduced in C++20 to simplify the syntax of function template definition. Traditionally, we use function templates to define a function that can take parameters of different types. But sometimes, it might get complicated and hard to understand. In these cases, we can implement an abbreviated function
3 min read
C++ Variable Templates
Over the years C++ has undergone advancements to improve its capabilities and coding efficiency. One notable addition in C++14 is the introduction of variable templates. These variable templates allow you to create a group of variables or static data members that can be customized providing flexibility for your code. Variable TemplatesVariable temp
4 min read
Why can templates only be implemented in the header file?
Templates are a powerful feature in C++ that allows for the creation of generic functions and classes. They provide a way to write code that works with different data types without sacrificing type safety. However, one notable restriction when working with templates is that their implementation is often required to be in the header file. This limit
4 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fu
2 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include&lt;iostream&gt; using namespace std; template&lt;class T, class U = char&gt; class A { public: T x; U y; }; int main() { A&lt;char
1 min read
Variadic function templates in C++
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C+
3 min read
Templates in C++ vs Generics in Java
While building large-scale projects, we need the code to be compatible with any kind of data which is provided to it. That is the place where your written code stands above that of others. Here what we meant is to make the code you write be generic to any kind of data provided to the program regardless of its data type. This is where Generics in Ja
4 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the 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 to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Article Tags :
Practice Tags :