How to create a new 2d vector with same dimensions as another 2d vector?

1.2k Views Asked by At

If I had an existing 2d vector (map) and I wanted to create another empty map, what would be the fastest/ most idiomatic way of doing that?

In this case, I'm working with images as 2d vectors of chars

I could iterate over the previous map

let mut new_image: Vec<Vec<char>> = image
        .iter()
        .map(|row| row.iter().map(|_| '.').collect())
        .collect();

I could use vec!

let mut new_image = vec![vec!['.'; image[0].len()]; image.len()];
1

There are 1 best solutions below

0
Frank Bryce On

Use

let mut new_image = vec![vec!['.'; image[0].len()]; image.len()];

It lines up with the canonical answer in this post. It's what I would expect to see, anyways.