Search code examples
vectorrustiteratorrangeslice

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?


Solution

  • 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.