Stack of Array in C++
To create a stack of arrays in C++, we can use the std::array container provided by the STL library. The std::array is a container that encapsulates fixed-size arrays. We can then create a stack of these arrays.
Syntax to Create Stack of Array in C++
stack<array<datatype, size>> stack_name;
Here,
- datatype denotes the type of data you want to store in the array.
- size denotes the size of each array present in the stack.
- stack_name is the name of the stack of array.
Note: The stack cannot be created with C-Style arrays as the type of the stack elements should be copy constructible and assignable.
C++ Program to Create a Stack of Arrays
The below program demonstrates how we can create a stack with an array in C++ STL.
// C++ Program to illustrate how to create a stack of arrays
#include <array>
#include <iostream>
#include <stack>
using namespace std;
int main()
{
// Define the type of array
typedef array<int, 3> ArrayType;
// Initialize two arrays
ArrayType array1 = { 1, 2, 3 };
ArrayType array2 = { 4, 5, 6 };
// Create a stack of arrays
stack<ArrayType> myStack;
myStack.push(array1);
myStack.push(array2);
// Print the stack of arrays
while (!myStack.empty()) {
ArrayType& topArray = myStack.top();
for (int i : topArray) {
cout << i << " ";
}
cout << endl;
myStack.pop();
}
return 0;
}
Output
4 5 6 1 2 3
Time Complexity: O(N), where N is the number of array.
Auxiliary Space: O(N * M), where M is the size of each array
How to Create a Stack of Arrays in C++?
In C++, the std::stack is a container that follows the LIFO (Last In, First Out) rule, whereas std::array is a sequence container that stores elements in contiguous memory. In this article, we will learn how to create a stack of an array in C++.
Example:
Input: arr1 = {1, 2, 3}; arr2 = {4, 5, 6}; arr3 = {7, 8, 9}; Output: Stack of Array: [ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} ]