Skip to content

Commit 93839c3

Browse files
committed
Add an example to show how to insert item to a sorted vec
1 parent 6f70adc commit 93839c3

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

Diff for: src/libcore/slice/mod.rs

+14
Original file line numberDiff line numberDiff line change
@@ -1364,6 +1364,20 @@ 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 = match s.binary_search(&num) {
1375+
/// Ok(idx) => idx,
1376+
/// Err(idx) => idx,
1377+
/// };
1378+
/// s.insert(idx, num);
1379+
/// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1380+
/// ```
13671381
#[stable(feature = "rust1", since = "1.0.0")]
13681382
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
13691383
where T: Ord

0 commit comments

Comments
 (0)