about summary refs log tree commit diff
diff options
context:
space:
mode:
authorLzu Tao <taolzu@gmail.com>2019-08-10 16:31:38 +0000
committerLzu Tao <taolzu@gmail.com>2019-08-10 16:31:38 +0000
commit93839c3fb4e3a3c3341595ac8dc2c7f4e39326d2 (patch)
tree620aec2b19ed5a8a3570ae1caca55bfd7549584a
parent6f70adcb18e5dc8df0672898a8404fd05a9c32cb (diff)
downloadrust-93839c3fb4e3a3c3341595ac8dc2c7f4e39326d2.tar.gz
rust-93839c3fb4e3a3c3341595ac8dc2c7f4e39326d2.zip
Add an example to show how to insert item to a sorted vec
-rw-r--r--src/libcore/slice/mod.rs14
1 files changed, 14 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs
index d5a34ea2bd5..29afc435996 100644
--- a/src/libcore/slice/mod.rs
+++ b/src/libcore/slice/mod.rs
@@ -1364,6 +1364,20 @@ impl<T> [T] {
     /// let r = s.binary_search(&1);
     /// assert!(match r { Ok(1..=4) => true, _ => false, });
     /// ```
+    ///
+    /// If you want to insert an item to a sorted vector, while maintaining
+    /// sort order:
+    ///
+    /// ```
+    /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+    /// let num = 42;
+    /// let idx = match s.binary_search(&num) {
+    ///     Ok(idx) => idx,
+    ///     Err(idx) => idx,
+    /// };
+    /// s.insert(idx, num);
+    /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
         where T: Ord