Skip to content

Commit 6bbd8c5

Browse files
committed
Auto merge of rust-lang#122945 - andy-k:sorted-vec-example, r=jhpratt
improve example on inserting to a sorted vector to avoid shifting equal elements
2 parents 31075bb + 6430296 commit 6bbd8c5

File tree

2 files changed

+9
-5
lines changed
  • library

2 files changed

+9
-5
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -2464,8 +2464,10 @@ impl<T, A: Allocator> VecDeque<T, A> {
24642464
///
24652465
/// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
24662466
/// let num = 42;
2467-
/// let idx = deque.partition_point(|&x| x < num);
2468-
/// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2467+
/// let idx = deque.partition_point(|&x| x <= num);
2468+
/// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2469+
/// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert`
2470+
/// // to shift less elements.
24692471
/// deque.insert(idx, num);
24702472
/// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
24712473
/// ```

library/core/src/slice/mod.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -2724,8 +2724,10 @@ impl<T> [T] {
27242724
/// ```
27252725
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
27262726
/// let num = 42;
2727-
/// let idx = s.partition_point(|&x| x < num);
2728-
/// // The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
2727+
/// let idx = s.partition_point(|&x| x <= num);
2728+
/// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2729+
/// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
2730+
/// // to shift less elements.
27292731
/// s.insert(idx, num);
27302732
/// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
27312733
/// ```
@@ -4175,7 +4177,7 @@ impl<T> [T] {
41754177
/// ```
41764178
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
41774179
/// let num = 42;
4178-
/// let idx = s.partition_point(|&x| x < num);
4180+
/// let idx = s.partition_point(|&x| x <= num);
41794181
/// s.insert(idx, num);
41804182
/// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
41814183
/// ```

0 commit comments

Comments
 (0)