Cover Image for C++ using the Stack Data Structure
118 views

C++ using the Stack Data Structure

Using the stack data structure in C++ is common for various tasks, such as managing function calls, implementing algorithms, and parsing expressions. Here’s an example of how to use the stack data structure in C++ to perform some basic operations:

C++
#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack; // Create an empty stack of integers

    // Push elements onto the stack
    myStack.push(10);
    myStack.push(20);
    myStack.push(30);

    // Check if the stack is empty
    if (myStack.empty()) {
        std::cout << "The stack is empty." << std::endl;
    } else {
        std::cout << "The stack is not empty." << std::endl;
    }

    // Get the size of the stack
    std::cout << "Size of the stack: " << myStack.size() << std::endl;

    // Access and print the top element
    std::cout << "Top element: " << myStack.top() << std::endl;

    // Pop elements from the stack
    myStack.pop();

    // Access and print the new top element
    std::cout << "Top element after pop: " << myStack.top() << std::endl;

    return 0;
}

In this program:

  1. We include the <stack> header to work with the stack data structure.
  2. We create a stack of integers using std::stack<int> myStack.
  3. Elements are pushed onto the stack using the push method.
  4. We check if the stack is empty using the empty method and print whether it’s empty or not.
  5. The size method is used to get the size of the stack.
  6. We access and print the top element of the stack using the top method.
  7. Elements are popped from the stack using the pop method.
  8. Finally, we access and print the new top element after a pop operation.

Compile and run this program to see how the stack data structure works in C++.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS