2-dimensional Vec

fn main() {
    let mut matris: Vec<Vec<i32>> = Vec::new();
    let mut row1: Vec<i32> = Vec::new();
    row1.push(1);
    row1.push(2);
    row1.push(3);
    row1.push(4);
    matris.push(row1);

    let mut row2: Vec<i32> = Vec::new();
    row2.push(5);
    row2.push(6);
    row2.push(7);
    row2.push(8);
    matris.push(row2);

    for index in &matris {
        for i in index {
            println!("Hello, world!---{}", i);
        }
        println!("next row!");
    }
    println!("Hello, world!");
}

(Playground)

Do you have a question about 2d vecs?

2 Likes

There are no 2-dimensional vectors in Rust. Vec<Vec> is a jagged array, not a 2d vec.

You need ndarray.

Well, if the inner Vecs are all of the same length, it's probably good enough of a 2d "Vec". The inner Vecs could also be converted into boxed slices after construction if wanted.

Ndarray is nice, but brings with it a lot of complexity that might be unnecessary. Often a struct holding a flat buffer with variables for stride and rows is good enough.

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.