Last active
October 30, 2023 14:53
-
-
Save timClicks/12c0ecbb4483628c0803d6de7c37a6af to your computer and use it in GitHub Desktop.
Making a practical priority queue from std::collections::BinaryHeap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:?}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage is explained in this video: https://youtu.be/nCNjzoKHtHk