Rollup merge of #135734 - nk9:extract_if-doc-equivalent, r=tgross35
Correct `extract_if` sample equivalent. Tracking issue: https://github.com/rust-lang/rust/issues/43244 Original PR: #133265 The sample code marked as equivalent in the doc comment isn't currently equivalent. Given the same predicate and range, if your vector were `[1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6]`, then all of the 3s would be removed. `i` is only incremented when an element is dropped, but `range.end` is unchanged, so the items shift down. I got very confused when reading the docs and trying to square this sample code with the explanation of how the function works. Fortunately, the real `extract_if()` does not have this problem. I've added an `end` variable to align the behavior. I've also taken the opportunity to simplify the predicate, which now just matches odd numbers, and to pad out the vec of numbers to line up the zero-indexed range with the integers in the vec. r? the8472
This commit is contained in:
commit
c44e1d65f3
1 changed files with 12 additions and 6 deletions
|
|
@ -3666,21 +3666,27 @@ impl<T, A: Allocator> Vec<T, A> {
|
|||
/// Using this method is equivalent to the following code:
|
||||
///
|
||||
/// ```
|
||||
/// # use std::cmp::min;
|
||||
/// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
|
||||
/// # let mut vec = vec![1, 2, 3, 4, 5, 6];
|
||||
/// # let range = 1..4;
|
||||
/// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
|
||||
/// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
|
||||
/// # let mut vec2 = vec.clone();
|
||||
/// # let range = 1..5;
|
||||
/// let mut i = range.start;
|
||||
/// while i < min(vec.len(), range.end) {
|
||||
/// let end_items = vec.len() - range.end;
|
||||
/// # let mut extracted = vec![];
|
||||
///
|
||||
/// while i < vec.len() - end_items {
|
||||
/// if some_predicate(&mut vec[i]) {
|
||||
/// let val = vec.remove(i);
|
||||
/// # extracted.push(val);
|
||||
/// // your code here
|
||||
/// } else {
|
||||
/// i += 1;
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// # assert_eq!(vec, vec![1, 4, 5]);
|
||||
/// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
|
||||
/// # assert_eq!(vec, vec2);
|
||||
/// # assert_eq!(extracted, extracted2);
|
||||
/// ```
|
||||
///
|
||||
/// But `extract_if` is easier to use. `extract_if` is also more efficient,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue