May 2019
Intermediate to advanced
698 pages
17h 21m
English
Removing the first item in a Vec<T> is not difficult—in fact, Vec<T> ships with a swap_remove() function that does exactly what a heap needs: removing the first element of a Vec<T> by replacing it with the last element! This makes the code significantly shorter and therefore easier to reason about:
pub fn pop(&mut self) -> Option<MessageNotification> { if self.length > 0 { let elem = self.heap.swap_remove(0); self.length = self.heap.len(); let mut i = 1; while i * 2 < self.length { let children = (i * 2, i * 2 + 1); i = if self.has_more_messages(children.0, children.1) { if self.has_more_messages(children.0, i) { self.swap(i, children.0); children.0 } else { break; } } else { if self.has_more_messages(children.1, i) { ...
Read now
Unlock full access