How do I shift the elements inside a Rust vector to the right and put the out-of-bounds element at the beginning?
You are looking for [T]::rotate_right
and [T]::rotate_left
. Example (Playground):
let mut v = vec![1, 2, 3, 4, 5];
v.rotate_right(1);
println!("{:?}", v);
This outputs:
[5, 1, 2, 3, 4]
If you find yourself calling rotate_*
a lot, you should consider using a different data structures, as those methods are linear time operations. See this answer, for example.
VecDeque
is a collection similar to a Vec
but optimized for adding/removing elements at either end. Just like slices, it has rotate_{left,right}
methods, but those are more efficient than Vec
's (O(min(mid, len() - mid))
time for VecDeque
, vs. O(len())
time for Vec
):
use std::collections::VecDeque;
fn main() {
let mut v = (1..6).collect::<VecDeque<_>>();
v.rotate_right(1);
println!("{:?}", v);
}
(Permalink to the playground)