How to push elements to an a 2d vector

how to push elements to an a 2d vector
let mut vec_2d:Vec<Vec> = Vec::new();

This construct is called jagged array. You have to first create a Vec for each row, e.g.

let jagged: Vec<Vec<Element>> = (0..height).map(|_| Vec::new()).collect();

Usually 2D vectors are made from a 1D Vec by addressing elements like vec[x + y*width]. You make such with vec![initial_value; width * height].

If you put your code in backticks like `<your code>`
It becomes much more readable.

what about using push() operator

rows.push(Vec::new()) adds a new row, and rows[y].push(value) adds a column in a given row.

2D vectors don't exist in Rust. You're working with 1D vector that contains more of 1D vectors, so all regular vec operations work, you just need to consider which of them to modify.

5 Likes

You can also push a new vector in your "root" vector:

let mut vec = Vec::new();
vec.push(Vec::new());
vec[0].push(0);

can you please explain the use of .map() and .collect()

.collect() makes a new container, in this case a Vec, from an iterator. And map() replaces elements in an iterator. I think it's better explained in the Rust Book, which I recommend reading.

1 Like

(0..height) creates an iterator with height many elements,
map(|_| Vec::new()) replaces each element with a Vec,
collect() then collects all these height many Vecs into a single collection (in this case a Vec).

1 Like

i try a different method
let mut vec_2d:Vec<Vec> = Vec::new();

for i in 0..5
{
    vec_2d.push(vec![]);
    for j in 0..5
    {
        vec_2d[i].push(j);
    }
    
}
println!("{:?}",vec_2d);

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.