std::stack
std::stack<T> is a last-in, first-out adapter. You push and pop at the top. It wraps an underlying container, by default std::deque<T>. Depth-first search and undo lists are stacks.
Detailed Explanation
A stack is a plate pile. The last plate you put down is the first you pick up. Expression evaluation, DFS, matching brackets, and "undo" are the usual applications. std::stack makes that the only available API.
push / emplace add to the top. top() is the current top. pop() removes it and returns void. empty and size forward. There are no iterators and no indexing.
The default underlying container is deque. std::stack<T, std::vector<T>> is a common choice: one allocation, contiguous storage, slightly better top locality. vector is a legal base because a stack only needs push_back, pop_back, and back. list works and is usually slower.
pop is void for the same exception-safety reason as queue::pop. Read top() first. top() on an empty stack is undefined behaviour.
The container adapter does not add thread safety. A shared stack needs a mutex.
You do not need std::stack to write a stack. A vector with push_back and pop_back is a stack, and you keep iterators if you want them. Use the adapter when you want the type system to stop you from touching the middle.
DFS uses a stack (or the call stack via recursion). Push the start, then while not empty, pop, visit, push unseen neighbours. Recursion is a stack you do not manage; an explicit stack is the version that will not overflow the native call stack on a deep graph.
Code Examples
#include <iostream>
#include <stack>
#include <string>
int main() {
std::stack<std::string> undo;
undo.push("type a");
undo.push("type b");
std::cout << undo.top() << '\n'; // prints: type b
undo.pop();
std::cout << undo.top() << '\n'; // prints: type a
}#include <stack>
#include <vector>
bool bracketsOk(const char* s) {
std::stack<char, std::vector<char>> st;
for (const char* p = s; *p; ++p) {
if (*p == '(') st.push('(');
else if (*p == ')') {
if (st.empty()) return false;
st.pop();
}
}
return st.empty();
}
int main() {
return bracketsOk("(())") && !bracketsOk("(()") ? 0 : 1;
}Common Gotchas
`pop()` returns `void`
capture `top()` before `pop()`.
`top()` on empty is undefined
check `empty()`.
Default underlying type is `deque`
pass `vector` as the second argument if you want contiguous storage.
Recursion is also a stack
converting a recursive DFS to `std::stack` is how you avoid overflowing the thread's stack on a deep graph.