Does cloning an iterator copy the entire underlying vector?

情到浓时终转凉″ 提交于 2021-01-04 03:14:10

问题


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);
    }
}

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);
    }
}

I looked at What's the most efficient way to reuse an iterator in 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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/45195454/does-cloning-an-iterator-copy-the-entire-underlying-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!