我试图将向量中的元素向右移动,然后将越界元素放回开头;向量的旋转。
这是在向量 1 步骤中移动第一个元素的伪代码。由于向量只有 5 个元素,因此5返回到向量的开头:
let V = vec![1, 2, 3, 4, 5];
A = V.move[0].cycle();
A = [5, 1, 2, 3, 4];
Run Code Online (Sandbox Code Playgroud)
这A = V.move[0].cycle();是我在这方面的尝试,但由于如果索引超出范围,Rust 不会旋转,因此可能难以实现。
在 Python 中,可以将该pop函数与列表一起使用:
let V = vec![1, 2, 3, 4, 5];
A = V.move[0].cycle();
A = [5, 1, 2, 3, 4];
Run Code Online (Sandbox Code Playgroud)
使用 for 循环,可以将所有元素移动为[5, 1, 2, 3, 4]. 是否有与popRust 中的函数等效的函数?如果有一个功能可以将元素一起移动,那就更好了。
Luk*_*odt 15
您正在寻找[T]::rotate_right和[T]::rotate_left。示例(游乐场):
let mut v = vec![1, 2, 3, 4, 5];
v.rotate_right(1);
println!("{:?}", v);
Run Code Online (Sandbox Code Playgroud)
这输出:
let mut v = vec![1, 2, 3, 4, 5];
v.rotate_right(1);
println!("{:?}", v);
Run Code Online (Sandbox Code Playgroud)
如果你发现自己调用rotate_*了很多,你应该考虑使用不同的数据结构,因为这些方法是线性时间操作。例如,请参阅此答案。
VecDeque是一个类似于 a 的集合,Vec但针对在任一端添加/删除元素进行了优化。就像切片一样,它也有rotate_{left,right}方法,但这些方法比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);
}
Run Code Online (Sandbox Code Playgroud)
(固定链接到操场)