Equinox
Equinox

Reputation: 140

Indexing a vector of vectors

Hello I am trying to create a 2D vector in rust simply by making a vector of vectors and then printing it in a 2D form.

Code:

fn draw_grid(grid:&Vec<Vec<i32>>){

for r in 0..grid.len(){
    for c in 0..grid.len(){
        print!("{}", grid[r[c]]);
    }
}

error:

error[E0608]: cannot index into a value of type `usize`

As you can see the compiler doesn't like it when I try to index it like a normal vector. Your help is greatly appreciated :)

Upvotes: 3

Views: 3716

Answers (2)

HJVT
HJVT

Reputation: 2192

You aren't indexing a vector, you are indexing an integer.

for r in 0..grid.len() {
    // r is an integer here
    for c in 0..grid.len() {
        // yet you are trying to index it as if it were an array: r[c]
        print!("{}", grid[r[c]]);
    }
}

The simple fix is to do print!("{}", grid[r][c]);.

However, the idiomatic way to iterate a vector in Rust is this:

for r in grid {
    for c in r {
        print!("{}", c);
    }
}

Upvotes: 5

mcarton
mcarton

Reputation: 30021

You're looking for grid[r][c].

  • grid is your vector of vector.
  • grid[r] is the r-th row, which is itself a vector.
  • grid[r][c], which can be seen as (grid[r])[c] if that helps, is element on the c-th column of that row.

Upvotes: 1

Related Questions