我想获得向量元素的所有组合。我正在使用 itertools 的组合()函数。很好,但现在我想操纵向量的元素。因此我需要一个迭代器来生成向量元素的可变引用......
我的代码基本上如下所示:
let mut v: Vec<MyType> = vec![];
for vpair in v.iter_mut().combinations(2) {
vpair.first().unwrap().do_something(vpair.last().unwrap());
}
Run Code Online (Sandbox Code Playgroud)
通过调用我想在每次迭代中do_something()操作vpair.first().unwrap()and 。vpair.last().unwrap()
我收到的错误是:
the trait std::clone::Clone is not implemented for &mut MyType
我能以某种方式解决这个问题还是我完全走错了路?
不,你不能这样做。定义itertools::Itertools::combinations为
fn combinations(self, k: usize) -> Combinations<Self>
where
Self: Sized,
Self::Item: Clone,
Run Code Online (Sandbox Code Playgroud)
它表示底层迭代器的项目需要是Clone. 毕竟,根据定义,所有组合都多次包含每个项目。但可变引用永远不会实现,Clone因为它是 Rust 独有的。
OTOH,如果你MyType是它自己Clone,你可以尝试:
let mut v: Vec<MyType> = vec![];
for vpair in v.into_iter().combinations(2) {
vpair.first().unwrap().do_something(vpair.last().unwrap());
}
Run Code Online (Sandbox Code Playgroud)
由于您拥有从 退回的物品into_iter,因此您可以对它们做任何您想做的事。但是每一轮循环都会操纵它们的独立克隆,这可能是也可能不是您想要做的。
| 归档时间: |
|
| 查看次数: |
7506 次 |
| 最近记录: |