Core Module
12 min forge
C++ STL Stack
Mastering Last-In-First-Out (LIFO) data structures.
C++ STL Stack
π What is it
std::stack is a container adaptor that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure.
β‘ When to use
Perfect for reversing data, depth-first searches (DFS) when used explicitly, matching brackets, and undo mechanisms.
π§ Time complexity
- Push: $O(1)$
- Pop: $O(1)$
- Top: $O(1)$
π» Code example
cpp Standard#include <stack> std::stack<int> s; s.push(1); s.push(2); std::cout << s.top(); // 2 s.pop(); std::cout << s.top(); // 1
β Common mistakes
- Empty Stack Pop: Trying to
pop()ortop()an empty stack (always checks.empty()first). - Forgetting that
pop()doesn't return the elementβit just removes it. - Using it when you need to access elements other than the top (use
std::vectorinstead).