How to Create Stack of Tuples in C++?
Last Updated :
06 Mar, 2024
In C++, a stack is a container adapter that provides a LIFO (Last In First Out) order of element insertion and deletion which is only possible at the end. A tuple is a container that can store elements of different types. In this article, we will learn how to create a stack of tuples in C++.
Example
Input:
myTuple1 = {1, “C++”, 4.5};
myTuple2 = {2, “Java”, 3.9};
Output:
myStack = [ {1, “C++”, 4.5},
{2, “Java”, 3.9} ]
Stack of Tuples in C++
To create a stack of tuples in C++, we have to declare the type of elements of the stack of type tuples by passing it as a template parameter in the stack declaration.
Syntax to Declare a Stack of Tuple in C++
stack< tuple< int, char>> tupleStack;
C++ Program to Create a Stack of Tuples
C++
#include <iostream>
#include <stack>
#include <tuple>
using namespace std;
int main()
{
tuple< int , string, double > myTuple1
= make_tuple(1, "C++" , 4.5);
tuple< int , string, double > myTuple2
= make_tuple(2, "Java" , 3.9);
stack<tuple< int , string, double > > myStack;
myStack.push(myTuple1);
myStack.push(myTuple2);
while (!myStack.empty()) {
tuple< int , string, double > topTuple = myStack.top();
myStack.pop();
cout << "{" << get<0>(topTuple) << ", "
<< get<1>(topTuple) << ", " << get<2>(topTuple)
<< "}, " ;
}
cout << endl;
return 0;
}
|
Output
{2, Java, 3.9}, {1, C++, 4.5},
Time Complexity: O(N).
Auxiliary Space: O(N * K), where is N number of tuples with K elements.
Share your thoughts in the comments
Please Login to comment...