C++ stack STL
In this page:
What is std::stack?
std::stack is a container adapter that provides Last-In-First-Out (LIFO) access. It wraps an underlying container (deque by default) and restricts access so elements can only be added or removed from the top.
Example: What is std::stack?
#include <iostream>
#include <stack>
int main() {
std::stack<int> s; // LIFO container adapter
s.push(1);
s.push(2);
std::cout << s.top() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
push(), pop() and top()
push() adds an element to the top. top() returns a reference to the top element without removing it. pop() removes the top element but does not return its value -- read it with top() first if you need it.
Example: push(), pop() and top()
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(10);
std::cout << s.top() << std::endl; // returns without removing
s.pop(); // removes without returning
std::cout << s.size() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
LIFO Behavior
The defining property of a stack is that the most recently pushed element is always the first one popped -- Last In, First Out. This makes it ideal for undo operations, function call tracking, and expression parsing.
Example: LIFO Behavior
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(1);
s.push(2);
s.push(3);
std::cout << s.top() << std::endl; // most recently pushed comes out first
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Checking empty() and size()
empty() returns true if the stack has no elements. size() returns the current element count. Always check empty() before calling top() or pop() to avoid undefined behavior.
Example: Checking empty() and size()
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
if (s.empty()) { // check before calling top()/pop() on an empty stack
std::cout << "Empty" << std::endl;
}
std::cout << s.size() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Practical Use: Balanced Parentheses
A classic stack use case is checking whether brackets in an expression are balanced -- push opening brackets, and pop and compare when a closing bracket is seen.
Example: Practical Use: Balanced Parentheses
#include <iostream>
#include <stack>
#include <string>
int main() {
std::string expr = "(()())";
std::stack<char> s;
bool balanced = true;
for (char c : expr) {
if (c == '(') s.push(c);
else if (!s.empty()) s.pop();
else balanced = false;
}
std::cout << (balanced && s.empty()) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: