简体   繁体   English

rust 多层循环中的向量迭代器

[英]rust vector iterator in multi-layer loop

I try to use iterator on vector slices, but it just doesn't work.我尝试在向量切片上使用迭代器,但它不起作用。

My code are as follows我的代码如下

  pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
        let mut res: Vec<Vec<i32>> = Vec::new();

        for (n1, &i1) in nums.iter().enumerate() {
            for (n2, &i2) in nums[(n1 + 1)..].iter().enumerate() {
                for (n3, &i3) in nums[(n2 + 1)..].iter().enumerate() {
                    if i1 + i2 + i3 == 0 {
                        res.push(Vec::from([i1, i2, i3]));
                    }
                }
            }
        }
        return res;
    }

I expected the n2 loop in nums ranging n1 to the end, but it just loop from the beginning, regardless of what n1 is.我希望 n2 循环以 nums 为单位,范围从 n1 到结尾,但它只是从头开始循环,而不管 n1 是什么。

Same happened on n3.同样发生在 n3 上。

Did I use iterators and slices correctly?我是否正确使用了迭代器和切片?

There is no way for enumerate to know where you want to start counting from so it always starts at 0. You can use zip with a range if you want to start counting from a different number. enumerate无法知道你想从哪里开始计数,所以它总是从 0 开始。如果你想从不同的数字开始计数,你可以使用zip和一个范围。

pub fn three_sum(nums: Vec<i32>) -> Vec<[i32;3]> {
    let mut res = Vec::new();

    for (n1, &i1) in nums.iter().enumerate() {
        for (n2, &i2) in (n1+1..).zip(nums[(n1 + 1)..].iter()) {
            for (n3, &i3) in (n2+1..).zip(nums[(n2 + 1)..].iter()) {
                if i1 + i2 + i3 == 0 {
                    res.push([i1, i2, i3]);
                }
            }
        }
    }
    res
}

As you can see in the docs , enumerate just counts the number of iterations.正如您在文档中看到的那样,枚举只计算迭代次数。 If you want to skip the first n elements of an iterator, you should use the skip function instead, which also more clearly expresses your intent.如果你想跳过一个迭代器的前n元素,你应该使用skip function来代替,这也更清楚地表达了你的意图。

nums.iter().enumerate().skip(n)

Note the order of enumerate and skip however: this way you're first constructing an enumerated iterator, then skipping some elements, so your index will also "start from" n .但是请注意enumerateskip的顺序:这样您首先构造一个枚举迭代器,然后跳过一些元素,因此您的索引也将“从” n开始。 The other way around you'll skip th elements first, then count them, starting from 0.反过来,你会先跳过 th 个元素,然后从 0 开始计算它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM