What is Stack in C++: Explanation and Example
stack is a container that stores elements in a last-in, first-out (LIFO) order. You can only add or remove elements from the top of the stack, making it useful for tasks like undo operations or tracking function calls.How It Works
Think of a stack like a stack of plates. You can only add a new plate on top or take the top plate off. This means the last plate you put on is the first one you take off. In C++, the stack container follows this same rule called Last-In, First-Out (LIFO).
When you add an element, it goes on the top of the stack. When you remove an element, it comes from the top as well. You cannot access elements in the middle or bottom directly. This makes stacks simple and fast for certain tasks.
Example
This example shows how to create a stack of integers, add numbers, and remove them while printing the top element.
#include <iostream> #include <stack> int main() { std::stack<int> s; s.push(10); // Add 10 s.push(20); // Add 20 s.push(30); // Add 30 std::cout << "Top element: " << s.top() << "\n"; // Should print 30 s.pop(); // Remove top (30) std::cout << "Top element after pop: " << s.top() << "\n"; // Should print 20 return 0; }
When to Use
Use a stack when you need to keep track of things in reverse order. For example, undo features in text editors use stacks to remember recent changes. Another common use is in function calls where the program remembers where to return after a function finishes.
Stacks are also helpful in parsing expressions, backtracking algorithms, and depth-first search in graphs.
Key Points
- A
stackstores elements in last-in, first-out order. - You can only add or remove elements from the top.
- Common operations are
push(add),pop(remove), andtop(view top element). - Stacks are useful for undo features, function call tracking, and certain algorithms.