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() or top() an empty stack (always check s.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::vector instead).