Create and populate a 2d vector
To create and populate a 2D vector in Rust, you can use the following code:
fn main() {
let mut vector_2d: Vec<Vec<i32>> = Vec::new();
let row1: Vec<i32> = vec![1, 2, 3];
let row2: Vec<i32> = vec![4, 5, 6];
let row3: Vec<i32> = vec![7, 8, 9];
vector_2d.push(row1);
vector_2d.push(row2);
vector_2d.push(row3);
println!("{:?}", vector_2d);
}
This code creates a 2D vector called vector_2d
using the Vec
type. It initializes an empty vector using Vec::new()
. Then, three rows are created as separate vectors (row1
, row2
, and row3
) using the vec!
macro. These rows are then pushed into the vector_2d
vector using the push
method.
Finally, the content of the 2D vector is printed using the println!
macro and the {:?}
format specifier.
Note: Make sure to include the Vec
module at the top of your code file with use std::vec::Vec;
to use the Vec
type.
I hope this helps! Let me know if you have any further questions.