How to Create a Stack of User-Defined Data Type in C++?
Last Updated :
11 Mar, 2024
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 type
StackName
is a stack of DataType
.
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++
#include <iostream>
#include <stack>
using namespace std;
struct Point {
int x, y;
};
int main()
{
stack<Point> stackOfPoints;
Point p1 = { 1, 2 };
Point p2 = { 3, 4 };
stackOfPoints.push(p1);
stackOfPoints.push(p2);
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)
Share your thoughts in the comments
Please Login to comment...