vector - How can I take an item from a Vec in Rust? -
what want method this:
fn take<t>(vec: vec<t>, index: usize) -> option<t>
however, can't find such method. missing something? or there reason unsafe / can't done correctly.
edit: different question built in *safe* way move out of vec<t>? there goal remove
method didn't panic on out of bounds access (that instead returned result.) here i'm looking method consumes vec, , returns 1 of elements. none of answers above question address question.
edit 2: clarify further, i'm looking method consumes vec , returns 1 element, without overhead of restoring vec's invariants way remove
, swap_remove
do.
you can write function this:
fn take<t>(mut vec: vec<t>, index: usize) -> option<t> { if vec.get(index).is_none() { none } else { some(vec.swap_remove(index)) } }
this guaranteed o(1).
to mention solution using iterators:
fn take<t>(vec: vec<t>, index: usize) -> option<t> { vec.into_iter().nth(index) }
i write this:
while
iterator::nth()
linear time operation, iterator on vector overrides method make o(1) operation.
but noticed, true iterator iterates on slices. std::vec::intoiter
iterator used in code above, doesn't override nth()
. has been attempted here, doesn't seem easy.
so: of right now, code above o(n) operation!
wiki
Comments
Post a Comment