TExcelTAD
Home › C++ › C++ Queue

C++ Queue

A queue is the opposite of a stack: the first element added is the first one removed — FIFO (First In, First Out). It works like a line at a ticket counter: people join at the back and are served from the front. std::queue lives in the <queue> header.

Basic operations

Member Effect
push(x) add x at the back
emplace(args...) construct a new element at the back
front() the element that will be removed next
back() the most recently added element
pop() remove the front element (returns nothing)
empty() / size() state of the queue
cpp · try it yourself
#include <iostream>
#include <queue>
#include <string>
using namespace std;

int main() {
    queue<string> line;
    line.push("Amir");
    line.push("Bea");
    line.push("Chen");

    cout << "front: " << line.front() << ", back: " << line.back() << "\n";

    while (!line.empty()) {
        cout << "serving " << line.front() << "\n";
        line.pop();
    }
}
front: Amir, back: Chen
serving Amir
serving Bea
serving Chen

Like stack, queue is a container adapter (built on deque by default) and cannot be iterated or indexed.

Example: round-robin scheduling

Operating systems share the CPU between tasks by giving each a short time slice, then moving it to the back of the queue if it is not finished:

cpp · try it yourself
#include <iostream>
#include <queue>
#include <string>
using namespace std;

struct Job {
    string name;
    int remaining;   // time units of work left
};

int main() {
    queue<Job> jobs;
    jobs.push({"A", 5});
    jobs.push({"B", 2});
    jobs.push({"C", 4});
    const int slice = 2;
    int clock = 0;

    while (!jobs.empty()) {
        Job j = jobs.front();
        jobs.pop();
        int work = min(slice, j.remaining);
        clock += work;
        j.remaining -= work;
        if (j.remaining > 0) {
            jobs.push(j);
        } else {
            cout << "job " << j.name << " finished at t=" << clock << "\n";
        }
    }
}
job B finished at t=4
job C finished at t=10
job A finished at t=11

Example: breadth-first search

Queues are at the heart of breadth-first search (BFS), which explores a graph level by level and finds shortest paths in unweighted graphs:

cpp · try it yourself
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int main() {
    // adjacency list of a small graph with nodes 0..5
    vector<vector<int>> adj = {
        {1, 2},     // 0
        {0, 3},     // 1
        {0, 3, 4},  // 2
        {1, 2, 5},  // 3
        {2, 5},     // 4
        {3, 4}      // 5
    };

    vector<int> dist(adj.size(), -1);
    queue<int> q;
    dist[0] = 0;
    q.push(0);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (int next : adj[node]) {
            if (dist[next] == -1) {
                dist[next] = dist[node] + 1;
                q.push(next);
            }
        }
    }

    for (size_t i = 0; i < dist.size(); i++) {
        cout << "node " << i << ": " << dist[i] << " steps\n";
    }
}
node 0: 0 steps
node 1: 1 steps
node 2: 1 steps
node 3: 2 steps
node 4: 2 steps
node 5: 3 steps

Priority queue

std::priority_queue (also in <queue>) always removes the largest element first, regardless of insertion order. Pass greater<> to get the smallest first instead:

cpp · try it yourself
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <string>
using namespace std;

int main() {
    priority_queue<int> maxHeap;
    for (int x : {5, 1, 8, 3, 9, 2}) maxHeap.push(x);
    while (!maxHeap.empty()) {
        cout << maxHeap.top() << " ";
        maxHeap.pop();
    }
    cout << "\n";

    // pairs compare by first element: (priority, task)
    priority_queue<pair<int, string>, vector<pair<int, string>>, greater<>> tasks;
    tasks.push({3, "write tests"});
    tasks.push({1, "fix production bug"});
    tasks.push({2, "review PR"});
    while (!tasks.empty()) {
        cout << tasks.top().first << ": " << tasks.top().second << "\n";
        tasks.pop();
    }
}
9 8 5 3 2 1
1: fix production bug
2: review PR
3: write tests

Note that a priority queue uses top(), not front().

Test yourself

Which order does std::queue use?

  1. LIFO
  2. FIFO
  3. Largest first
  4. Sorted

After pushing 4, 7, 1 into a std::queue, what is front()?

  1. 4
  2. 7
  3. 1
  4. Undefined

Which element does a default std::priority_queue<int> return from top()?

  1. The oldest
  2. The newest
  3. The largest
  4. The smallest