Remove item from vector

Is there an easy way to remove an item from Vec<T> ?

There is a remove() method, and it accepts index: usize , but there is not even an index_of() method that I see.

I am looking for something (hopefully) simple and O (n).

+9
source share
4 answers

This is what I have come up with so far (which also does a check check):

 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 it is pretty ugly.

Note: my code assumes the element exists (hence .unwrap() ).

+12
source

There is a position() method for iterators that returns the index of the first element matching the predicate. Related question: Is there a JavaScript equivalent of indexOf for Rust arrays?

And an example code:

 fn main() { let mut vec = vec![1, 2, 3, 4]; println!("Before: {:?}", vec); let removed = vec.iter() .position(|&n| n > 2) .map(|e| vec.remove(e)) .is_some(); println!("Did we remove anything? {}", removed); println!("After: {:?}", vec); } 
+9
source

There is an experimental API called Vec::remove_item() . It is still unstable, so it cannot be used with a stable compiler. But in the end, it probably stabilizes ( tracking ).

Using this method, doing what you want is very simple:

 let removed = xs.remove_item(&some_x); 
+7
source

You can use the retain method but it will delete each 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] } 
+5
source

Source: https://habr.com/ru/post/976372/


All Articles