Is there a simple way to remove an element from a Vec<T>
?
There's a method called remove()
, and it takes an index: usize
, but there isn't even an index_of()
method that I can see.
I'm looking for something (hopefully) simple and O(n).
To delete an item at specific index from R Vector, pass the negated index as a vector in square brackets after the vector. We can also delete multiple items from a vector, based on index.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable. To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1).
This is what I have come up so far (that also makes the borrow checker happy):
let index = xs.iter().position(|x| *x == some_x).unwrap(); xs.remove(index);
I'm still waiting to find a better way to do this as this is pretty ugly.
Note: my code assumes the element does exist (hence the .unwrap()
).
You can use the retain
method but it will delete every instance of the value:
fn main() { let mut xs = vec![1, 2, 3]; let some_x = 2; xs.retain(|&x| x != some_x); println!("{:?}", xs); // prints [1, 3] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With