Skip to content

Module 8 · The Standard Template Library — topic 4 of 7

Stacks, Queues and Priority Queues

Container adaptors give restricted interfaces: LIFO stacks, FIFO queues and priority queues. Use them for bracket matching, BFS, scheduling and top-k problems.

Beginner 13 min read·Lesson 34 of 40 in C++ Programming

Learning objectives

  • Use stack, queue and priority_queue operations
  • Apply stacks and queues to classic problems
  • Build a min-heap with a custom comparator

Definition

std::stack (LIFO), std::queue (FIFO) and std::priority_queue (highest-priority-first) are container adaptors that provide a limited interface over an underlying container (deque by default, vector for priority_queue).

Introduction

Many algorithms only need the most recent item (undo, matching brackets, depth-first search) or the oldest item (print queues, breadth-first search) or the most important item (task scheduling). Adaptors give you exactly those operations and nothing that could misuse the data.

An adaptor is not a new data structure: it wraps an existing container (a deque by default for stack and queue, a vector for priority_queue) and exposes a deliberately small interface. You can choose the underlying container as a template argument when you need different performance characteristics.

Why it matters

Stacks and queues are fundamental data structures in DSA courses and interviews.

priority_queue solves scheduling and top-k problems in O(log n) per operation.

Detailed explanation

stack: push, pop, top, empty, size. queue: push, pop, front, back. priority_queue: push, pop, top (largest by default).

pop() returns void; read top()/front() first. Calling top/pop on an empty adaptor is undefined behaviour.

Min-heap: std::priority_queue<int, std::vector<int>, std::greater<int>>. Custom ordering uses a comparator that returns true when the first argument has lower priority.

None of the adaptors supports iteration.

Syntax

C++
std::stack<char> st; st.push('('); st.top(); st.pop();
std::queue<int> q; q.push(1); q.front(); q.pop();
std::priority_queue<int> maxh;
std::priority_queue<int, std::vector<int>, std::greater<int>> minh;
  • Include <stack> and <queue>.
  • Always check empty() before top/front/pop.
  • priority_queue is a binary heap.

Code examples

Balanced brackets with a stack

C++
#include <iostream>
#include <stack>
#include <string>
bool balanced(const std::string& s) {
std::stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') st.push(c);
else if (c == ')' || c == ']' || c == '}') {
if (st.empty()) return false;
char o = st.top();
st.pop();
if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{')) return false;
}
}
return st.empty();
}
int main() {
for (std::string s : {"{[()]}", "([)]", "(("}) std::cout << s << ' ' << balanced(s) << '\n';
return 0;
}
Output
{[()]} 1
([)] 0
(( 0

A FIFO queue

C++
#include <iostream>
#include <queue>
#include <string>
int main() {
std::queue<std::string> printer;
for (std::string job : {"report.pdf", "photo.png", "notes.txt"}) printer.push(job);
while (!printer.empty()) {
std::cout << "printing " << printer.front() << '\n';
printer.pop();
}
return 0;
}
Output
printing report.pdf
printing photo.png
printing notes.txt

More examples

Task scheduling with a priority queue

C++
#include <iostream>
#include <queue>
#include <string>
#include <vector>
struct Task {
int priority; // 1 = most urgent
int order; // arrival order for ties
std::string name;
};
struct LowerPriority {
bool operator()(const Task& a, const Task& b) const {
if (a.priority != b.priority) return a.priority > b.priority; // larger number = lower priority
return a.order > b.order;
}
};
int main() {
std::priority_queue<Task, std::vector<Task>, LowerPriority> pq;
int n = 0;
pq.push({3, n++, "write notes"});
pq.push({1, n++, "fix server"});
pq.push({2, n++, "reply email"});
pq.push({1, n++, "pay fees"});
while (!pq.empty()) {
std::cout << pq.top().priority << ' ' << pq.top().name << '\n';
pq.pop();
}
std::priority_queue<int, std::vector<int>, std::greater<int>> minh;
for (int x : {7, 2, 9, 4}) minh.push(x);
std::cout << "smallest: " << minh.top() << '\n';
return 0;
}
Output
1 fix server
1 pay fees
2 reply email
3 write notes
smallest: 2

Step-by-step explanation

  • The comparator returns true when a should come out after b.
  • Priority 1 tasks come first; among equals, earlier arrivals win.
  • std::greater<int> turns the default max-heap into a min-heap.
  • Each push/pop is O(log n).

Expected output

Running “Task scheduling with a priority queue” prints exactly:

TextOutput
1 fix server
1 pay fees
2 reply email
3 write notes
smallest: 2

Practical applications

  • Compilers use stacks to parse nested expressions.
  • Breadth-first search uses a queue.
  • Operating systems and Dijkstra's algorithm use priority queues.

Best practices

  • Check empty() before top/front/pop.
  • Use a named comparator struct for complex priorities.
  • Add a sequence number to make heap ordering stable.

Common mistakes

Expecting pop() to return the value

Avoid

int x = st.pop();

Prefer

int x = st.top();
st.pop();

pop returns void in all adaptors.

Popping an empty stack

Avoid

st.pop(); // st may be empty

Prefer

if (!st.empty()) st.pop();

top/pop on an empty adaptor is undefined behaviour.

Important notes

  • priority_queue is not stable by itself; equal elements may come out in any order unless you add a tie-breaker.
  • std::deque can serve as both a stack and a queue when you need iteration.

Key takeaways

  • stack = LIFO, queue = FIFO, priority_queue = best first.
  • pop() returns void.
  • Use greater<> or a comparator for min-heaps.

Try it yourself

  1. 1
    Evaluate a postfix expression like "3 4 + 2 *" with a stack.
  2. 2
    Find the k largest numbers in a vector using a min-heap of size k.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat does `std::priority_queue<int>` return from top() by default?
Practise this topic