C++ stack and queue adapters

Compare LIFO and FIFO removal on the same values.

C++
#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';
}
Output
3 1
2 2

Explanation

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.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2#include <stack>
3#include <queue>
4int main() {
5 std::stack<int> stack;
6 std::queue<int> queue;
7 for (int value : {1, 2, 3}) { stack.push(value); queue.push(value); }
8 std::cout << stack.top() << ' ' << queue.front() << '\n';
9 stack.pop();
10 queue.pop();
11 std::cout << stack.top() << ' ' << queue.front() << '\n';
12}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

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.

Further reading