Rust Reference ยท Collections
Rust Vec insert, remove and swap_remove
Reference for Vec::insert, remove, swap_remove and replace in Rust: shifting cost, panics on bad indexes, order-preserving versus O(1) removal.
insert(index, value) puts an element at a position and shifts everything after it one slot to the right. remove(index) takes an element out and shifts the tail left to close the gap, returning the removed value. Both keep the order of the remaining elements and cost O(n) in the worst case.
swap_remove(index) is the fast alternative: it removes an element by moving the last element into its place. That is O(1), but the order changes. Pick it when a vector is really a bag of items.
let mut v = vec![10, 20, 30]; v.insert(1, 15); // [10, 15, 20, 30] let gone = v.remove(0); // 10
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Vec<T> { pub fn insert(&mut self, index: usize, element: T); pub fn remove(&mut self, index: usize) -> T; pub fn swap_remove(&mut self, index: usize) -> T; }
| Name | Description |
|---|---|
index |
Position to insert at or remove from. For insert it may equal len(); for the removers it must be less than len(). |
element |
The value to insert, moved into the vector. |
Returns: insert returns nothing. remove and swap_remove return the removed element by value.
Panics: insert panics when index > len. remove and swap_remove panic when index >= len. The message states both numbers.
Usage notes
- Cost:
insertandremovemovelen - indexelements, so removing from the front of a large vector repeatedly is quadratic. UseVecDequefor front operations, ordrainto remove many items in one pass. swap_removechanges order. If you must keep order, useremove. If you need to delete the last element,popis cleaner.- Inserting may reallocate when
len == capacity. Insertion into the middle never keeps old references valid, which the borrow checker enforces. - Removing while iterating does not compile if you iterate by reference. Collect indexes first, use
retain, or loop backwards over indexes. - Take, don't clone.
removehands you ownership, so no clone is needed to move aStringout of a vector.std::mem::take(&mut v[i])leaves a default value behind without shifting anything. - Replace in place: assign with
v[i] = new(drops the old value) or usestd::mem::replaceto get the old value back. - Related slice methods:
swap(a, b)exchanges two positions, androtate_leftmoves a block (seeswap, reverse, rotate). Vec::removereturnsT, notOption<T>. Contrast withHashMap::remove, which returns anOption.
Related
Vec<T>,retain, dedup, drain,Vec::new, push, pop,VecDeque<T>- Lessons: Vectors, Ownership