0

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()];
Lacrosse343
  • 491
  • 1
  • 3
  • 18
  • Do you want it to reuse the heap allocation? Or do you just want to have two vecs of the same size? – MeetTitan Jan 03 '22 at 14:27
  • 2
    note that there is a difference between both versions: If the length of the rows is different (`image[0].len() != image[1].len()`) the first version would create vectors of different lengths and the second version would create vectors of the length of only the first vector! – Akida Jan 03 '22 at 14:28
  • Also your second vec is always (only?) as wide as the first row of chars. This may not be an issue with grid datatypes where your 2d grid is a rectangular matrix with even row lengths, but you should check indices. – MeetTitan Jan 03 '22 at 14:30
  • 1
    The fastest and (arguably) most idiomatic way of working with a 2D map is to use a single `Vec` of length `width*height`, possibly wrapped in a `struct` that adds helper function for easy access by coordinates. – Jmb Jan 03 '22 at 15:03
  • Oh, and the only possible answer to "what is the fastest…?" is: benchmark in release mode in your configuration. We can suggest different approaches, but you won't be sure that they are really faster until you measure them in _your_ environment. – Jmb Jan 03 '22 at 15:05

1 Answers1

0

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.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56