snippetrustCritical
How to remove an element from a vector given the element?
Viewed 0 times
howfromremovetheelementvectorgiven
Problem
Is there a simple way to remove an element from a
There's a method called
I'm looking for something (hopefully) simple and O(n).
Vec?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).
Solution
This is what I have come up so far (that also makes the borrow checker happy):
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
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()).Context
Stack Overflow Q#26243025, score: 130
Revisions (0)
No revisions yet.