C++ stack and queue adapters
Compare LIFO and FIFO removal on the same values.
On this page
Container operations and conditions.
- Compare LIFO and FIFO removal on the same values.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
std::stack exposes a last-in, first-out interface, while std::queue exposes a first-in, first-out interface. They adapt underlying containers rather than exposing arbitrary indexing.
top or front reads an item; pop removes it and returns no value. Check emptiness before accessing or popping.
Code example
#include <iostream>
#include <stack>
#include <queue>
int main() {
std::stack<int> stack;
std::queue<int> queue;
for (int value : {1, 2, 3}) { stack.push(value); queue.push(value); }
std::cout << stack.top() << ' ' << queue.front() << '\n';
stack.pop();
queue.pop();
std::cout << stack.top() << ' ' << queue.front() << '\n';
}3 1 2 2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <iostream>#include <stack>#include <queue>int main() { std::stack<int> stack; std::queue<int> queue; for (int value : {1, 2, 3}) { stack.push(value); queue.push(value); } std::cout << stack.top() << ' ' << queue.front() << '\n'; stack.pop(); queue.pop(); std::cout << stack.top() << ' ' << queue.front() << '\n';}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Insert 1, 2, then 3 into both. | stack bottom->top: 1,2,3; queue front->back: 1,2,3 | — | |
| Read newest stack item and oldest queue item. | stack bottom->top: 1,2,3; queue front->back: 1,2,3 | 3 1 | |
| Remove 3 from the stack. | stack top = 2 | 3 1 | |
| Remove 1 from the queue. | queue front = 2 | 3 1 | |
| The second print reads 2 from each. | queue front = 2 | 3 1 2 2 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
Cost and common mistakes
O(1) endpoint operations with the default deque backing; O(n) stored elements.
- These pop methods do not return the removed value.
- Accessing top or front on an empty adapter violates its preconditions.
Try it yourself
Remove one more item from each and predict the next pair.
Reveal answer and reasoning
The stack top is 1 and the queue front is 3.