How to iterate over a two dimensional vector in rust?

1.3k Views Asked by At

I have a mutable reference of vector of mutable references of vectors I want to iterate over the vector and then change the value of its elements.

let mut a = vec![1, 2, 3];
let mut b = vec![4, 5, 6];
let mut c = vec![&mut a , &mut b];
let mut v = &mut c;

I want to iterate over v and do operations on its elements preferably using an iterator and not by indexing.(I specifically want to iterate over a reference of a vector of references of vector and not just a 2d vector)

1

There are 1 best solutions below

0
Finomnis On BEST ANSWER
fn main() {
    let mut a = vec![1, 2, 3];
    let mut b = vec![4, 5, 6];
    let mut c = vec![&mut a, &mut b];
    let v = &mut c;

    for row in v.iter_mut() {
        for el in row.iter_mut() {
            *el *= 2;
        }
    }

    println!("{:?}", v);
}
[[2, 4, 6], [8, 10, 12]]

Or if you need the indices for the computation:

fn main() {
    let mut a = vec![1, 2, 3];
    let mut b = vec![4, 5, 6];
    let mut c = vec![&mut a, &mut b];
    let v = &mut c;

    for (y, row) in v.iter_mut().enumerate() {
        for (x, el) in row.iter_mut().enumerate() {
            *el *= 2 * x + y;
        }
    }

    println!("{:?}", v);
}
[[0, 4, 12], [4, 15, 30]]