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++
// C++ Program to illustrate how to create a stack of tuples #include <iostream> #include <stack> #include <tuple> using namespace std;
int main()
{ // Initialize two tuples
tuple< int , string, double > myTuple1
= make_tuple(1, "C++" , 4.5);
tuple< int , string, double > myTuple2
= make_tuple(2, "Java" , 3.9);
// Create a stack of tuples
stack<tuple< int , string, double > > myStack;
myStack.push(myTuple1);
myStack.push(myTuple2);
// Print the stack of tuples
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.