Open In App

How to Create a Stack of Strings in C++?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Output

Stack is not empty.

Time Complexity: O(N) where N is the number of strings.
Auxiliary Space: O(N)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads