Creating a Stack of Strings in C++
To create a std::stack of std::string, we can use the std::stack template class that takes the type of the elements as a template parameter. We can define this type as std::string.
Syntax to Declare Stack of Strings
std::stack<std::string> myStack
C++ Program to Create a Stack of Strings
C++
// C++ program to illustrate how to create a stack of // strings string #include <iostream> #include <stack> using namespace std; int main() { // Declaring a stack of strings stack<string> myStack; // Pushing strings into the stack myStack.push( "Hello" ); myStack.push( "World" ); // Checking if the stack is empty if (myStack.empty()) { cout << "Stack is empty." << endl; } else { cout << "Stack is not empty." << endl; } return 0; } |
Stack is not empty.
Time Complexity: O(N) where N is the number of strings.
Auxiliary Space: O(N)
How to Create a Stack of Strings in C++?
In C++, Stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn how to create a stack of strings in C++.