How to Create a Stack of User-Defined Data Type in C++?
In C++, we have a stack data structure that follows the LIFO (Last In First Out) rule and allows operations such as push, pop, and top at one end of the structure. In this article, we will learn how to create a stack of user-defined data types in C++.
Example:
Input:
//user defined data type
struct Point {
int x, y;
};
Output:
Elements in the Stack of Point:
(3, 4)
(1, 2)
Creating Stack of a User-Defined Datatype in C++
The process of creating a std::stack of user-defined data types is similar to creating a stack of built-in data types, but instead of using a built-in data type, we have to use a user-defined data type as template argument. For that, first create a custom class or struct and then use a std::stack::push() to store instances of that type.
Syntax to Create Stack of User-Defined Data Type in C++
stack<DataType> StackName;
Here,
DataType
is a name of user-defined data typeStackName
is a stack ofDataType
.
C++ Program to Use a Stack with a User-Defined Data Type
The below program demonstrates how we can create a stack of user-defined data types in C++.
// C++ Program to show how to create and use a Stack of a
// User-Defined Data Type
#include <iostream>
#include <stack>
using namespace std;
// User-defined data type
struct Point {
int x, y;
};
int main()
{
// Creating a stack of Points
stack<Point> stackOfPoints;
// Creating Points
Point p1 = { 1, 2 };
Point p2 = { 3, 4 };
// Pushing Points into the stack
stackOfPoints.push(p1);
stackOfPoints.push(p2);
// Printing elements from the stack of Points
cout << "Elements in the Stack of Points:" << endl;
while (!stackOfPoints.empty()) {
Point currP = stackOfPoints.top();
stackOfPoints.pop();
cout << "(" << currP.x << ", " << currP.y << ")"
<< endl;
}
return 0;
}
Output
Elements in the Stack of Points: (3, 4) (1, 2)
Time Complexity: O(N), here n is the total number of elements in the stack.
Auxiliary Space: O(N)