How can I push data to 2D vector

I've the below 2d vector, how can I push/insert data into it.

main(){
    let mut 2d_vec: Vec<Vec<f64>> = Vec::new();
   // let mut 2d_vec = vec![vec![0.0f64; columns as usize]; rows as usize];

    2d_vec[w][h] = [1.0, 2.0];
}

I got this error:

error[E0277]: the type `[std::vec::Vec<f64>]` cannot be indexed by `u32`
  --> src/main.rs:63:13
   |
63 |             2d_vec[w][h] =  [1.0, 2.0]; 
   |             ^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[std::vec::Vec<f64>]>` is not implemented for `u32`
   = note: required because of the requirements on the impl of `std::ops::Index<u32>` for `std::vec::Vec<std::vec::Vec<f64>>`

this works

fn main(){
    let columns = 100;
    let rows = 100;
    let mut v = vec![vec![0.0; columns as usize]; rows as usize];

    // set value at 10,10 to 1.0
    let x: u32 = 10;
    let y: u32 = 10;
    v[x as usize][y as usize] = 1.0;
}

but not sure what kind of behavior you expect when you say 'push'? should it expand the grid as necessary? if so, you'd need to write custom functionality to do that

(also mind that this "2D vector" is not really a 2D vector but a vector of 1D vectors so not every column necessarily has the same length, this has to be ensured at a higher level)

1 Like

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