splpriorityqueue

SplPriorityQueue implements Iterator, Countable

A max-heap priority queue: insert(value, priority) enqueues, extract dequeues, top peeks, isEmpty checks — extraction always yields the highest priority, but the order of equal-priority items is undefined (the demo uses distinct priorities for determinism); the extraction mode is tunable via setExtractFlags.

C C23

C23
#include <stdio.h>

#define CAP 16
static int pri[CAP];
static const char *data[CAP];
static int n = 0;

static void swap(int i, int j) { /* exchange two heap nodes */
    int tp = pri[i]; pri[i] = pri[j]; pri[j] = tp;
    const char *td = data[i]; data[i] = data[j]; data[j] = td;
}
static void sift_up(int i) { /* bubble a node toward the root */
    while (i > 0) {
        int parent = (i - 1) / 2;
        if (pri[parent] >= pri[i]) break;
        swap(parent, i);
        i = parent;
    }
}
static void sift_down(int i) { /* push the root down to its place */
    for (;;) {
        int l = 2 * i + 1, r = l + 1, big = i;
        if (l < n && pri[l] > pri[big]) big = l;
        if (r < n && pri[r] > pri[big]) big = r;
        if (big == i) break;
        swap(big, i);
        i = big;
    }
}
static void insert(int p, const char *d) {
    pri[n] = p; data[n] = d; n++;
    sift_up(n - 1);
}
static const char *extract(void) { /* take the root, move the last node up */
    const char *top = data[0];
    n--;
    if (n > 0) { pri[0] = pri[n]; data[0] = data[n]; sift_down(0); }
    return top;
}

int main(void) {
    insert(1, "email");
    insert(3, "pager");
    insert(2, "sms");
    insert(0, "log");
    printf("%d\n", n);          /* 4 */
    printf("%d\n", n == 0);     /* 0 = false */
    while (n > 0) printf("%s\n", extract()); /* highest priority first */
    printf("%d\n", n == 0);     /* 1 = true */
    return 0;
}
Output
4
0
pager
sms
email
log
1

C++ C++26

C++26
#include <iostream>
#include <queue>
#include <string>
#include <utility>

int main() {
    // max-heap by default: pair compares by priority, then by data
    std::priority_queue<std::pair<int, std::string>> q;
    q.emplace(1, "email");
    q.emplace(3, "pager");
    q.emplace(2, "sms");
    q.emplace(0, "log");
    std::cout << q.size() << "\n";     // 4
    std::cout << std::boolalpha;
    std::cout << q.empty() << "\n";    // false
    while (!q.empty()) {
        std::cout << q.top().second << "\n"; // highest priority first
        q.pop();
    }
    std::cout << q.empty() << "\n";    // true
    return 0;
}
Output
4
false
pager
sms
email
log
true

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;

// min-based queue + reversed comparer = max-first like SplPriorityQueue
var q = new PriorityQueue<string, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
q.Enqueue("email", 1);
q.Enqueue("pager", 3);
q.Enqueue("sms", 2);
q.Enqueue("log", 0);
Console.WriteLine(q.Count);      // 4
Console.WriteLine(q.Count == 0); // False
while (q.Count > 0) {
    Console.WriteLine(q.Dequeue()); // highest priority first
}
Console.WriteLine(q.Count == 0); // True
Output
4
False
pager
sms
email
log
True

Go v1.27.4

v1.27.4
package main

import (
	"container/heap"
	"fmt"
)

// container/heap asks you to implement the queue yourself (heap.Interface)
type pqueue [][2]string // each item: [priority, data]

func (q pqueue) Len() int            { return len(q) }
func (q pqueue) Less(i, j int) bool  { return q[i][0] > q[j][0] } // max-first
func (q pqueue) Swap(i, j int)       { q[i], q[j] = q[j], q[i] }
func (q *pqueue) Push(x any)         { *q = append(*q, x.([2]string)) }
func (q *pqueue) Pop() any {
	old := *q
	n := len(old)
	item := old[n-1]
	*q = old[:n-1]
	return item
}

func main() {
	q := &pqueue{}
	heap.Push(q, [2]string{"1", "email"})
	heap.Push(q, [2]string{"3", "pager"})
	heap.Push(q, [2]string{"2", "sms"})
	heap.Push(q, [2]string{"0", "log"})
	fmt.Println(q.Len())       // 4
	fmt.Println(q.Len() == 0)  // false
	for q.Len() > 0 {
		fmt.Println(heap.Pop(q).([2]string)[1]) // highest priority first
	}
	fmt.Println(q.Len() == 0)  // true
}
Output
4
false
pager
sms
email
log
true

Java v27.0.1

v27.0.1
import java.util.Comparator;
import java.util.Map;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // PriorityQueue is a min-heap; reverse the comparator to pop the max first
        PriorityQueue<Map.Entry<Integer, String>> q = new PriorityQueue<>(
                Comparator.<Map.Entry<Integer, String>>comparingInt(Map.Entry::getKey).reversed());
        q.add(Map.entry(1, "email"));
        q.add(Map.entry(3, "pager"));
        q.add(Map.entry(2, "sms"));
        q.add(Map.entry(0, "log"));
        System.out.println(q.size());     // 4
        System.out.println(q.isEmpty());  // false
        while (!q.isEmpty()) {
            System.out.println(q.poll().getValue()); // highest priority first
        }
        System.out.println(q.isEmpty());  // true
    }
}
Output
4
false
pager
sms
email
log
true

JavaScript v26.13.1

v26.13.1
// JS has no built-in priority queue: emulate with an array kept sorted
const q = [];
const insert = (data, priority) => {
  q.push([data, priority]);
  q.sort((x, y) => y[1] - x[1]); // highest priority first
};
insert("email", 1);
insert("pager", 3);
insert("sms", 2);
insert("log", 0);
console.log(q.length);       // 4
console.log(q.length === 0); // false
const out = [];
while (q.length > 0) out.push(q.shift()[0]); // extract from the front
console.log(out.join(" "));
console.log(q.length === 0); // true
Output
4
false
pager sms email log
true

PHP v8.6.0

v8.6.0
$q = new SplPriorityQueue();
$q->insert("email", 1);
$q->insert("pager", 3);
$q->insert("sms", 2);
$q->insert("log", 0);
var_dump($q->count());         // 4
var_dump($q->isEmpty());       // false
while (!$q->isEmpty()) {
    echo $q->extract(), "\n";  // highest priority first
}
var_dump($q->isEmpty());       // true
Output
int(4)
bool(false)
pager
sms
email
log
bool(true)

Python v3.15.2

v3.15.2
import heapq

# heapq is a min-heap: negate priorities to pop the highest first
q = []
heapq.heappush(q, (-1, "email"))
heapq.heappush(q, (-3, "pager"))
heapq.heappush(q, (-2, "sms"))
heapq.heappush(q, (0, "log"))
print(len(q))           # 4
print(len(q) == 0)      # False
out = []
while q:
    _, data = heapq.heappop(q)
    out.append(data)
print(" ".join(out))    # highest priority first
print(len(q) == 0)      # True
Output
4
False
pager sms email log
True

Rust v1.99.1

v1.99.1
use std::collections::BinaryHeap;

fn main() {
    // BinaryHeap is a max-heap: (priority, data) pops the highest first
    let mut q: BinaryHeap<(i32, &str)> = BinaryHeap::new();
    q.push((1, "email"));
    q.push((3, "pager"));
    q.push((2, "sms"));
    q.push((0, "log"));
    println!("{}", q.len());       // 4
    println!("{}", q.is_empty());  // false
    let mut out = Vec::new();
    while let Some((_, data)) = q.pop() {
        out.push(data);
    }
    println!("{}", out.join(" "));
    println!("{}", q.is_empty());  // true
}
Output
4
false
pager sms email log
true

TypeScript v26.13.1

v26.13.1
// TS has no built-in priority queue either: emulate with a sorted array
const q: Array<[string, number]> = [];
const insert = (data: string, priority: number): void => {
  q.push([data, priority]);
  q.sort((x, y) => y[1] - x[1]); // highest priority first
};
insert("email", 1);
insert("pager", 3);
insert("sms", 2);
insert("log", 0);
console.log(q.length);       // 4
console.log(q.length === 0); // false
const out: string[] = [];
while (q.length > 0) out.push(q.shift()![0]);
console.log(out.join(" "));
console.log(q.length === 0); // true
Output
4
false
pager sms email log
true

Language differences

C: no container library — hand-roll a binary heap (array-based complete tree + sift_up/sift_down); insert/extract are both O(log n); the demo prints 1/0 for true/false.

C++: std::priority_queue is a max-heap by default, and pair(priority, data) compares the first element first — equal priorities fall through to the data, so ties are deterministic but unrelated to insertion order.

C#: PriorityQueue<TElement, TPriority> (.NET 6+) is natively a min queue (lowest priority dequeued first) — the opposite of SplPriorityQueue; the demo reverses the comparer to align "highest first".

Go: container/heap is interface-based: the heap stores nothing — you implement Len/Less/Swap/Push/Pop on your own type (Push/Pop use pointer receivers to mutate the slice) — a unique but flexible design; writing > in Less makes it a max-heap.

Java: PriorityQueue is a min-heap; a reversed() comparator flips it to max-first semantics; Map.entry carries the (priority, data) pair.

JavaScript: no native priority queue — the demo emulates one with insert-and-sort (O(n log n) per insert; fine for teaching, write a real heap or use a heap library in production).

PHP: SplPriorityQueue is a max-heap (subclass and override compare() to customize); insert($value, $priority) enqueues, extract() dequeues, top() peeks; setExtractFlags(EXTR_BOTH/EXTR_PRIORITY) can include the priority in the extracted value (default EXTR_DATA yields only the data). Note the dequeue order of equal-priority items is undefined (documented) — the demo deliberately uses distinct priorities for determinism; class constants are typed since 8.4.

Python: heapq is native but a min-heap — the idiom is to push negated priorities for max-first behavior; items are (-priority, data) tuples, and equal priorities compare the data next, so mixed incomparable types need care.

Rust: BinaryHeap is a native max-heap and the (i32, &str) tuple is directly Ord; equal priorities fall back to lexicographic data order — deterministic but unrelated to insertion order.

TypeScript: same as JS — no native structure; the sorted-array emulation stands.