🧱 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; }
🛠️ Common Stack Functions
push()
– Add item to toppop()
– Remove item from toptop()
– View the top itemempty()
– Check if stack is emptysize()
– 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; }
✅ Summary
- Stack = Last In, First Out (LIFO)
- Perfect for undo, backtracking, and reversing
- Include
<stack>
and use simple functions