How to Create a Stack of Strings in C++?
Last Updated :
04 Mar, 2024
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++.
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++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<string> myStack;
myStack.push( "Hello" );
myStack.push( "World" );
if (myStack.empty()) {
cout << "Stack is empty." << endl;
}
else {
cout << "Stack is not empty." << endl;
}
return 0;
}
|
Output
Stack is not empty.
Time Complexity: O(N) where N is the number of strings.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...