Skip to content

Instantly share code, notes, and snippets.

@timClicks
Last active October 30, 2023 14:53
Show Gist options
  • Save timClicks/12c0ecbb4483628c0803d6de7c37a6af to your computer and use it in GitHub Desktop.
Save timClicks/12c0ecbb4483628c0803d6de7c37a6af to your computer and use it in GitHub Desktop.
Making a practical priority queue from std::collections::BinaryHeap
use std::collections::BinaryHeap;
// Create a type that implements Ord to represent your tasks. That can be
// fed into BinaryHeap with a tuple, using its first field representing priority,
//
// > "When derived on enums, variants are ordered by their discriminants"
// > - https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html#derivable
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
enum Task {
A,
B,
C,
}
// You might like to implement PartialOrd yourself, rather than having
// the different task categories be able to out-rank each other:
// impl PartialOrd for Task {
// fn partial_cmp(&self, _: &Task) -> Option<std::cmp::Ordering> {
// Some(std::cmp::Ordering::Equal)
// }
// }
fn main() {
let mut queue = BinaryHeap::new();
queue.push((1, Task::A));
queue.push((1, Task::B));
queue.push((2, Task::C));
queue.push((0, Task::C));
queue.push((1, Task::A));
queue.push((1, Task::C));
while let Some((priority, task)) = queue.pop() {
println!("{_priority} {task:?}");
}
}
@timClicks
Copy link
Author

timClicks commented Jul 25, 2023

Usage is explained in this video: https://youtu.be/nCNjzoKHtHk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment