Vec<Vec<char>> cannot be built from Iter<Vec<char>>

Hi, I'm working on the Advent of Code 2021 (day 3, part 2) and I was hoping I could get some help.

This is my code so far:

fn filter(mut lines: Vec<Vec<char>>, key: &[char]) -> Vec<Vec<char>> {
    for i in 0.. {
        lines = lines
            .iter()
            .filter(|chars| chars[i] == key[i])
            .collect();

        if lines.len() == 1 {
            return lines
        }
    }

    panic!("inifnite loop stopped by itself");
}

the minimum viable problem can be boiled down into:

let a: Vec<Vec<char>> = Vec::new();

let b: Vec<Vec<char>> = a.iter().collect();

The error I get is that "a value of type Vec<Vec<char>> cannot be built from an iterator over elements of type &Vec<char>."

I suspected the problem may have had to do with heap allocation, so I tried it with primitives:

let a: Vec<u32> = Vec::new();

let b: Vec<u32> = a.iter().collect();

However, this failed for the same reason! I was wondering if anyone could explain why this is the case? I had always thought that .collect() just undid what .iter() does.

Thanks

Can you try:

a.into_iter().collect()

or

a.iter().cloned().collect() (slower, clones the Vec)

1 Like

vec.iter() iterates over references to the contents of the Vec, while vec.into_iter() iterates over the actual contents of the Vec (consuming the Vec in the process). Hence @zeroexcuses suggestion to try .into_vec() (or cloning).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.