You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vec.rs 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. pub trait InsertMany {
  2. type Element;
  3. fn insert_many(&mut self, elem_to_insert: Vec<(usize, Self::Element)>);
  4. }
  5. impl<T> InsertMany for Vec<T> {
  6. type Element = T;
  7. /// Efficiently insert multiple element in their specified index.
  8. /// The elements should sorted in ascending order by their index.
  9. ///
  10. /// This is done in O(n) time.
  11. fn insert_many(&mut self, elem_to_insert: Vec<(usize, T)>) {
  12. let mut inserted = vec![];
  13. let mut last_idx = 0;
  14. for (idx, elem) in elem_to_insert.into_iter() {
  15. let head_len = idx - last_idx;
  16. inserted.extend(self.splice(0..head_len, std::iter::empty()));
  17. inserted.push(elem);
  18. last_idx = idx;
  19. }
  20. let len = self.len();
  21. inserted.extend(self.drain(0..len));
  22. *self = inserted;
  23. }
  24. }
  25. #[cfg(test)]
  26. mod test {
  27. use super::InsertMany;
  28. #[test]
  29. fn insert_many_works() {
  30. let mut v = vec![1, 2, 3, 4, 5];
  31. v.insert_many(vec![(0, 0), (2, -1), (5, 6)]);
  32. assert_eq!(v, &[0, 1, 2, -1, 3, 4, 5, 6]);
  33. let mut v2 = vec![1, 2, 3, 4, 5];
  34. v2.insert_many(vec![(0, 0), (2, -1)]);
  35. assert_eq!(v2, &[0, 1, 2, -1, 3, 4, 5]);
  36. }
  37. }