克隆迭代器是否会复制整个基础向量? [英] Does cloning an iterator copy the entire underlying vector?

查看:60
本文介绍了克隆迭代器是否会复制整个基础向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历一个向量几次:

I would like to iterate over a vector several times:

let my_vector = vec![1, 2, 3, 4, 5];
let mut out_vector = vec![];
for i in my_vector {
    for j in my_vector {
        out_vector.push(i * j + i + j);
    }
}

j循环具有移动后在此处使用的值"错误.我知道我可以在两个my_vector之前放置一个&并借用这些向量,但是有多种方法可以很好地完成工作.我也想了解一点.

The j-loop has a "value used here after move" error. I know that I can place an & before the two my_vectors and borrow the vectors, but it is nice to have more than one way to do things. I would like a little insight as well.

或者,我可以写以下内容:

Alternatively, I can write the following:

let i_vec = vec![1, 2, 3, 4, 5, 6];
let iterator = i_vec.iter();
let mut out_vec = vec![];
for i in iterator.clone() {
    for j in iterator.clone() {
        out_vec.push(i * j + i + j);
    }
}

我查看了什么是最有效的在Rust中重用迭代器的方法是什么?:

如果迭代器的所有片段"都是可克隆的,则它们通常是可克隆的.

Iterators in general are Clone-able if all their "pieces" are Clone-able.

实际分配的堆数据是迭代器的片段",还是指向堆数据的内存地址?

Is the actual heap allocated data a "piece" of the iterator or is it the memory address that points to the heap data the aforementioned piece?

推荐答案

克隆切片迭代器(这是在Vec或数组上调用iter()时得到的迭代器的类型)不会复制基础数据.这两个迭代器仍指向原始向量中存储的数据,因此克隆操作很便宜.

Cloning a slice iterator (this is the type of iterator you get when calling iter() on a Vec or an array) does not copy the underlying data. Both iterators still point to data stored in the original vector, so the clone operation is cheap.

其他类型的可克隆迭代器也可能如此.

The same is likely true for clonable iterators on other types.

在您的情况下,您也可以多次调用i_vec.iter()来代替调用i_vec.iter()然后克隆它:

In your case, instead of calling i_vec.iter() and then cloning it, you can also call i_vec.iter() multiple times:

for i in i_vec.iter() {
    for j in i_vec.iter() {

给出相同的结果,但可读性更高.

which gives the same result but is probably more readable.

这篇关于克隆迭代器是否会复制整个基础向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆