C++ Stack
A stack is a collection where the last element added is the first one removed — LIFO (Last In, First Out). Think of a stack of plates: you put new plates on top, and you take plates from the top. std::stack from the <stack> header provides exactly this behaviour.
Basic operations
| Member | Effect |
|---|---|
push(x) |
put x on top |
emplace(args...) |
construct a new element on top |
top() |
access the top element (without removing it) |
pop() |
remove the top element (returns nothing) |
empty() |
true if there are no elements |
size() |
number of elements |
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
stack<string> plates;
plates.push("red");
plates.push("green");
plates.push("blue");
cout << "top: " << plates.top() << ", size: " << plates.size() << "\n";
while (!plates.empty()) {
cout << "taking " << plates.top() << "\n";
plates.pop();
}
}top: blue, size: 3
taking blue
taking green
taking red
Notice that pop() does not return the removed value — read it with top() first. Calling top() or pop() on an empty stack is undefined behaviour, so check empty().
Note:
std::stackis a container adapter: it wraps another container (dequeby default) and only exposes the stack operations. There is no iteration and no indexing — on purpose.
Example: undo history
Stacks are the natural structure for "undo": each action is pushed, and undo pops the most recent one:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string text;
stack<string> history;
auto type = [&](const string& s) {
history.push(text);
text += s;
cout << "typed -> \"" << text << "\"\n";
};
auto undo = [&]() {
if (history.empty()) return;
text = history.top();
history.pop();
cout << "undo -> \"" << text << "\"\n";
};
type("Hello");
type(", world");
type("!!!");
undo();
undo();
type(" there");
}typed -> "Hello"
typed -> "Hello, world"
typed -> "Hello, world!!!"
undo -> "Hello, world"
undo -> "Hello"
typed -> "Hello there"
Example: balanced brackets
A classic interview problem: are all brackets in a string correctly matched? Push every opening bracket; on a closing bracket, the top of the stack must be its partner:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool balanced(const string& s) {
stack<char> open;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
open.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (open.empty()) return false;
char expected = (c == ')') ? '(' : (c == ']') ? '[' : '{';
if (open.top() != expected) return false;
open.pop();
}
}
return open.empty();
}
int main() {
string tests[] = {"(a[b]{c})", "((x)", "{[}]", "f(g[0]) + {}"};
for (const auto& t : tests) {
cout << t << " -> " << (balanced(t) ? "balanced" : "NOT balanced") << "\n";
}
}(a[b]{c}) -> balanced
((x) -> NOT balanced
{[}] -> NOT balanced
f(g[0]) + {} -> balanced
Example: evaluating postfix expressions
In postfix (Reverse Polish) notation, 3 4 + 2 * means (3 + 4) * 2. A stack evaluates it in one pass:
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
int evalPostfix(const string& expr) {
stack<int> st;
istringstream in(expr);
string token;
while (in >> token) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (token == "+") st.push(a + b);
else if (token == "-") st.push(a - b);
else if (token == "*") st.push(a * b);
else st.push(a / b);
} else {
st.push(stoi(token));
}
}
return st.top();
}
int main() {
cout << evalPostfix("3 4 + 2 *") << "\n";
cout << evalPostfix("5 1 2 + 4 * + 3 -") << "\n";
}14
14
Stacks also power function calls themselves (the call stack), depth-first search, and the "back" button in your browser.
Test yourself
Which order does a stack use?
- FIFO
- LIFO
- Sorted
- Random
What does pop() return in std::stack?
- The removed element
- A boolean
- Nothing (void)
- The new top
After pushing 1, 2, 3 and popping once, what is top()?
- 1
- 2
- 3
- Empty