How to Create a Stack of Vectors in C++?
In C++, a stack of vectors can be created using the Standard Template Library (STL). The stack is a container adapter that provides a Last-In-First-Out (LIFO) type of data structure, and a vector is a dynamic array that can grow and shrink in size. In this article, we will learn how to create a stack of vectors in C++.
Example
Input: myVector1 = { 1, 4, 3, 2, 10} myVector2 = {5, 1, 3, 4, 8} Output: myStack: [ { 1, 4, 3, 2, 10},
{5, 1, 3, 4, 8} ]
Stack of Vectors in C++
To create a std::stack of std::vector, we can define the type of stack as the std::vector by passing it as the template parameter. In this way, each element of the stack will be a vector.
Syntax to Declare a Stack of Vector
stack <vector <type>> myStack;
C++ Program to Create a Stack of Vectors
C++
// C++ Program to illustrate how to create a stack of // vectors #include <iostream> #include <stack> #include <vector> using namespace std; int main() { // Declaring a stack of vectors stack<vector< int > > myStack; // Creating some vectors vector< int > vec1 = { 1, 2, 3 }; vector< int > vec2 = { 4, 5, 6 }; vector< int > vec3 = { 7, 8, 9 }; // Pushing vectors into the stack myStack.push(vec1); myStack.push(vec2); myStack.push(vec3); // printing the stack cout << "MyStack:" << endl; while (!myStack.empty()) { auto ele = myStack.top(); cout << " {" ; for ( auto i : ele) { cout << i << " " ; } cout << "}" << endl; myStack.pop(); } return 0; } |
Output
MyStack: {7 8 9 } {4 5 6 } {1 2 3 }
Time Complexity: O(N), where N is the number of vectors.
Auxiliary Space: O(N)
Contact Us