In C++, std::stack<T> is a container adaptor from the <stack> header that keeps the newest element on top. You add with push() or emplace(), peek with top(), and remove with pop(). That order is called last in, first out (LIFO).
A stack is usually backed by a std::deque. You do not need to manage that yourself. The daily pattern is simple: push() to add, top() to read the top, and pop() to remove it. Use empty() before you read or remove.
This page teaches what a stack is. The stack Functions index lists every function guide in this series.
You can only see the top.
A stack has no [], no at(), and no begin() or end(). You cannot loop over all elements with iterators. Reading or removing from an empty stack with top() or pop() is undefined behavior, so check empty() first. Unlike priority_queue, a non-const top() returns a reference you can assign through.
Syntax
C++ Syntax
Common ways to create and use a std::stack:
C++
#include <deque>
#include <iostream>
#include <stack>
#include <vector>
std::stack<int> st; // default: backed by deque
std::stack<int, std::vector<int>> stVec; // optional: backed by vector
st.push(10);
st.push(40);
st.emplace(20); // C++11
int newest = st.top(); // 20
st.top() = 25; // assign through the reference
st.pop(); // removes 25, returns nothing
std::size_t n = st.size(); // 2
bool none = st.empty(); // false
Reference
The LIFO Pattern
Think of a stack of plates. You only touch the top plate:
Both containers receive 3, 9, 1 in the same order. Both use push(), pop(), and empty().
std::stack is last in, first out (LIFO). It reads with top() and gives the newest first: 1 9 3.
std::queue is first in, first out (FIFO). It reads with front() and gives the numbers back as they arrived: 3 9 1. A priority_queue would instead keep the largest on top.
Continue
Next: C++ stack Functions Index
After you know what a stack is for, open the function index for a full tutorial on each function.
std::stack is a container adaptor from the <stack> header. It is last in, first out (LIFO): you push and emplace on top, read with top(), and remove with pop(). It is usually backed by a deque.
stack is LIFO (newest first) and reads with top(). queue is FIFO (oldest first) and reads with front(). priority_queue is a max-heap by default and also reads with top(), but the top is the highest priority, not the newest.
No. pop() returns void. Read the value with top() first, then call pop(). Calling top() or pop() on an empty stack is undefined behavior.
Yes, on a non-const stack. top() returns a reference, so you can assign through it (for example st.top() = 99). Prefer that only when you mean to edit the top element in place.
Open the C++ std::stack Functions index. It lists all 8 member functions with a short description, the C++ version needed, and a full tutorial for each.