Skip to content

Commit 787eddc

Browse files
author
arlo
committed
Add BinaryHeap::retain as suggested in #42849
1 parent 00f677d commit 787eddc

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/liballoc/collections/binary_heap.rs

+28
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,34 @@ impl<T: Ord> BinaryHeap<T> {
665665
pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
666666
DrainSorted { inner: self }
667667
}
668+
669+
/// Retains only the elements specified by the predicate.
670+
///
671+
/// In other words, remove all elements `e` such that `f(&e)` returns
672+
/// `false`. The elements are visited in unsorted (and unspecified) order.
673+
///
674+
/// # Examples
675+
///
676+
/// Basic usage:
677+
///
678+
/// ```
679+
/// #![feature(binary_heap_retain)]
680+
/// use std::collections::BinaryHeap;
681+
///
682+
/// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
683+
///
684+
/// heap.retain(|x| x % 2 == 0); // only keep even numbers
685+
///
686+
/// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
687+
/// ```
688+
#[unstable(feature = "binary_heap_retain", issue = "71503")]
689+
pub fn retain<F>(&mut self, f: F)
690+
where
691+
F: FnMut(&T) -> bool,
692+
{
693+
self.data.retain(f);
694+
self.rebuild();
695+
}
668696
}
669697

670698
impl<T> BinaryHeap<T> {

src/liballoc/tests/binary_heap.rs

+8
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,14 @@ fn assert_covariance() {
372372
}
373373
}
374374

375+
#[test]
376+
fn test_retain() {
377+
let mut a = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
378+
a.retain(|x| x % 2 == 0);
379+
380+
assert_eq!(a.into_sorted_vec(), [-10, 2, 4])
381+
}
382+
375383
// old binaryheap failed this test
376384
//
377385
// Integrity means that all elements are present after a comparison panics,

src/liballoc/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#![feature(binary_heap_drain_sorted)]
1515
#![feature(vec_remove_item)]
1616
#![feature(split_inclusive)]
17+
#![feature(binary_heap_retain)]
1718

1819
use std::collections::hash_map::DefaultHasher;
1920
use std::hash::{Hash, Hasher};

0 commit comments

Comments
 (0)