简体   繁体   中英

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.

Same happened on 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.

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.

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 . The other way around you'll skip th elements first, then count them, starting from 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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