Skip to content

Commit 407536e

Browse files
committed
Auto merge of #60451 - rasendubi:binaryheap-min-heap, r=scottmcm
BinaryHeap: add min-heap example Fixes #58174.
2 parents 03bd2f6 + adbaf7a commit 407536e

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/liballoc/collections/binary_heap.rs

+24
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,30 @@ use super::SpecExtend;
207207
/// // The heap should now be empty.
208208
/// assert!(heap.is_empty())
209209
/// ```
210+
///
211+
/// ## Min-heap
212+
///
213+
/// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
214+
/// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
215+
/// value instead of the greatest one.
216+
///
217+
/// ```
218+
/// use std::collections::BinaryHeap;
219+
/// use std::cmp::Reverse;
220+
///
221+
/// let mut heap = BinaryHeap::new();
222+
///
223+
/// // Wrap values in `Reverse`
224+
/// heap.push(Reverse(1));
225+
/// heap.push(Reverse(5));
226+
/// heap.push(Reverse(2));
227+
///
228+
/// // If we pop these scores now, they should come back in the reverse order.
229+
/// assert_eq!(heap.pop(), Some(Reverse(1)));
230+
/// assert_eq!(heap.pop(), Some(Reverse(2)));
231+
/// assert_eq!(heap.pop(), Some(Reverse(5)));
232+
/// assert_eq!(heap.pop(), None);
233+
/// ```
210234
#[stable(feature = "rust1", since = "1.0.0")]
211235
pub struct BinaryHeap<T> {
212236
data: Vec<T>,

0 commit comments

Comments
 (0)