2d vector rust
To use a 2D vector in Rust, you can use a nested Vec
structure. Here's an example:
fn main() {
let mut matrix: Vec<Vec<i32>> = Vec::new();
for i in 0..3 {
let mut row: Vec<i32> = Vec::new();
for j in 0..3 {
row.push(i * j);
}
matrix.push(row);
}
println!("{:?}", matrix);
}
In this example, we create a 2D vector called matrix
using the Vec<Vec<i32>>
type. We then iterate over the rows and columns of the matrix and populate it with values. Finally, we print the matrix using println!
macro.
The output of this code will be:
[[0, 0, 0], [0, 1, 2], [0, 2, 4]]
This represents a 3x3 matrix where each element is the product of its row and column indices.
You can access individual elements of the matrix using the indexing syntax, like matrix[row_index][column_index]
. For example, to access the element at row 1, column 2 (which is 2
), you can use matrix[1][2]
.
I hope this helps! Let me know if you have any further questions.