未验证 提交 e20ca112 编写于 作者: D Dylan DPC 提交者: GitHub

Rollup merge of #71485 - arlopurcell:binary_heap_retain, r=Amanieu

Add BinaryHeap::retain as suggested in #42849

This PR implements retain for BinaryHeap as suggested in #42849.

This is my first PR for Rust, so please let me know if I should be doing anything differently, thanks!
......@@ -665,6 +665,34 @@ fn better_to_rebuild(len1: usize, len2: usize) -> bool {
pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
DrainSorted { inner: self }
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns
/// `false`. The elements are visited in unsorted (and unspecified) order.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(binary_heap_retain)]
/// use std::collections::BinaryHeap;
///
/// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
///
/// heap.retain(|x| x % 2 == 0); // only keep even numbers
///
/// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
/// ```
#[unstable(feature = "binary_heap_retain", issue = "71503")]
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&T) -> bool,
{
self.data.retain(f);
self.rebuild();
}
}
impl<T> BinaryHeap<T> {
......
......@@ -372,6 +372,14 @@ fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
}
}
#[test]
fn test_retain() {
let mut a = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
a.retain(|x| x % 2 == 0);
assert_eq!(a.into_sorted_vec(), [-10, 2, 4])
}
// old binaryheap failed this test
//
// Integrity means that all elements are present after a comparison panics,
......
......@@ -14,6 +14,7 @@
#![feature(binary_heap_drain_sorted)]
#![feature(vec_remove_item)]
#![feature(split_inclusive)]
#![feature(binary_heap_retain)]
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册