How is the stack used in C++?

In C++, a stack is a container that stores data and accesses it in Last In, First Out (LIFO) order. The stack can store any type of data, including built-in types (such as int, float) and user-defined types.

The primary operations of stack include:

  1. push(elem): Add the element elem to the top of the stack.
  2. pop(): Remove an element from the top of the stack.
  3. top(): returns the element at the top of the stack without removing it.
  4. empty(): check if the stack is empty.
  5. size(): Returns the number of elements in the stack.

Here is a simple example using a stack.

#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack;

    myStack.push(10);
    myStack.push(20);
    myStack.push(30);

    std::cout << "Stack size: " << myStack.size() << std::endl;
    std::cout << "Top element: " << myStack.top() << std::endl;

    myStack.pop();

    std::cout << "Stack size: " << myStack.size() << std::endl;
    std::cout << "Top element: " << myStack.top() << std::endl;

    return 0;
}

Output results:

Stack size: 3
Top element: 30
Stack size: 2
Top element: 20

This example first creates an integer stack (std::stack myStack), then uses the push() method to sequentially add three elements (10, 20, 30) to the stack. The size() method is then used to get the size of the stack, and the top() method is used to get the top element (30) of the stack. The pop() method is then used to remove the top element, and the size() and top() methods are used again to display the updated stack.

Please note that in order to use stack, you need to include the header file .

bannerAds