Skip to content

Commit e16b12f

Browse files
authoredAug 11, 2019
Rollup merge of rust-lang#63442 - lzutao:vec-bin-search-insert, r=Mark-Simulacrum
Add an example to show how to insert item to a sorted vec Closes rust-lang#61684 cc rust-lang#61742 r? @Mark-Simulacrum, @jonas-schievink
2 parents c805a38 + 30ba4bd commit e16b12f

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed
 

‎src/libcore/slice/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -1364,6 +1364,17 @@ impl<T> [T] {
13641364
/// let r = s.binary_search(&1);
13651365
/// assert!(match r { Ok(1..=4) => true, _ => false, });
13661366
/// ```
1367+
///
1368+
/// If you want to insert an item to a sorted vector, while maintaining
1369+
/// sort order:
1370+
///
1371+
/// ```
1372+
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1373+
/// let num = 42;
1374+
/// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1375+
/// s.insert(idx, num);
1376+
/// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1377+
/// ```
13671378
#[stable(feature = "rust1", since = "1.0.0")]
13681379
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
13691380
where T: Ord

0 commit comments

Comments
 (0)
Please sign in to comment.