C++ Stack

🧱 C++ Stack – Last In, First Out (LIFO) in Action

A stack in C++ works like a pile of plates—the last one you put on is the first you take off. This is called LIFO: Last In, First Out.

Stacks are super useful when you need to reverse things, like undo actions or manage recursive calls.

📦 How to Use stack in C++

You need to include the <stack> header:

#include <stack>
using namespace std;

stack<int> myStack;

🔧 Example: Stack Operations

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> s;

    s.push(100);
    s.push(200);
    s.push(300);

    cout << "Top: " << s.top() << endl;

    s.pop(); // Removes the top

    cout << "After pop, top: " << s.top() << endl;

    return 0;
}
  

Try It Now

🛠️ Common Stack Functions

  • push() – Add item to top
  • pop() – Remove item from top
  • top() – View the top item
  • empty() – Check if stack is empty
  • size() – Number of items

🎯 Example: Stack Check

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> numbers;

    if (numbers.empty()) {
        cout << "Stack is empty!" << endl;
    }

    numbers.push(1);
    numbers.push(2);
    numbers.push(3);

    cout << "Stack size: " << numbers.size() << endl;

    return 0;
}
  

Try It Now

✅ Summary

  • Stack = Last In, First Out (LIFO)
  • Perfect for undo, backtracking, and reversing
  • Include <stack> and use simple functions