![](/img/trans.png)
[英]How do I remove the elements of vector that occur in another vector in Rust?
[英]How do I shift the elements inside a Rust vector to the right and put the out-of-bounds element at the beginning?
我试图将向量中的元素向右移动,然后将越界元素放回开头; 向量的旋转。
这是在向量 1 步骤中移动第一个元素的伪代码。 由于向量只有 5 个元素,所以5
回到向量的开头:
let V = vec![1, 2, 3, 4, 5];
A = V.move[0].cycle();
A = [5, 1, 2, 3, 4];
A = V.move[0].cycle();
这是我的尝试,但由于如果索引超出范围,Rust 不会旋转,因此可能难以实现。
在 Python 中,可以将pop
函数与列表一起使用:
>>>m = [1, 2, 3, 4, 5]
>>>m += [m.pop(0)]
>>>m
[2, 3, 4, 5, 1]
使用 for 循环,可以将所有元素移动为[5, 1, 2, 3, 4]
。 是否有与 Rust 中的pop
函数等效的函数? 如果有一个功能可以将元素一起移动,那就更好了。
您正在寻找[T]::rotate_right
和[T]::rotate_left
。 示例( 游乐场):
let mut v = vec![1, 2, 3, 4, 5];
v.rotate_right(1);
println!("{:?}", v);
这输出:
[5, 1, 2, 3, 4]
如果您发现自己rotate_*
调用rotate_*
,您应该考虑使用不同的数据结构,因为这些方法是线性时间操作。 例如,请参阅此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.