C++ std::stack: Last-In First-Out (LIFO) Container Adapter & Real Use Cases

std::stack is a Container Adapter that provides a strict LIFO (Last-In, First-Out) interface on top of an underlying container (by default, std::deque).

Classic Interview Problem: Balanced Parentheses Checker

#include <iostream>
#include <stack>
#include <string>

bool isBalanced(const std::string& expr) {
    std::stack<char> s;
    for (char ch : expr) {
        if (ch == '(' || ch == '{' || ch == '[') {
            s.push(ch);
        } else if (ch == ')' || ch == '}' || ch == ']') {
            if (s.empty()) return false;
            char top = s.top();
            s.pop();
            if ((ch == ')' && top != '(') ||
                (ch == '}' && top != '{') ||
                (ch == ']' && top != '[')) {
                return false;
            }
        }
    }
    return s.empty();
}

int main() {
    std::cout << std::boolalpha;
    std::cout << "{[()]} is balanced: " << isBalanced("{[()]}") << "\n"; // true
    std::cout << "{[(])} is balanced: " << isBalanced("{[(])}") << "\n"; // false
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why doesn't std::stack::pop() return the value it popped?

For Exception Safety! If pop() returned the value by value, copying the object might throw an exception after the element was already removed from the stack, permanently losing the element. Therefore, top() reads the value and pop() removes it.

Q2. Can you iterate through a std::stack with a for loop?

No. A container adapter intentionally hides iterators to enforce strict LIFO semantics. To access all elements, you must process top() and pop() until empty().

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

std::queue

Compare LIFO stack vs FIFO queue.

std::deque

The default underlying container of std::stack.

Call Stack

Understanding the CPU's hardware call stack.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!