Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from a vector

Tags:

rust

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).

like image 374
Kai Sellgren Avatar asked Oct 07 '14 18:10

Kai Sellgren


People also ask

How do I remove an element from a vector in R?

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.

How do you delete an element from a vector by its value?

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.

How do you remove an element from a vector in a loop?

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).


2 Answers

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()).

like image 65
Kai Sellgren Avatar answered Oct 21 '22 05:10

Kai Sellgren


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] } 
like image 29
antoyo Avatar answered Oct 21 '22 06:10

antoyo