Vector of vectors, iteration, reference to precedent

hell, I am just new to rust :slight_smile:
I need to iterate a vector of vectors, and in the loop I need also to reference the precedent element (a vector)

THIS COMPILES, normal iteration:
//create vectors of vectors
let mut rows :Vec<Vec>= std::vec::Vec::new();

// create five rows
for _iterate_rows in 0..5 {
    let mut row : Vec<i32> = std::vec::Vec::new();
    //put 10 numbers in each row
    for iterate_numbers in 0..10 {
        row.push (iterate_numbers);
    }
    rows.push (row);
}

//loop the whole structure: ok, it compiles
for actual_row in &rows {
    print!("row - ");
    
    for actual_number in actual_row {
        
        print!("n:{}",actual_number);
    }
    println!(" ");
}

THIS DOES NOT COMPILE, iteration with precedent:
//loop the whole structure with precedent row in memory: no ok, it does not compile
let precedent_row : Vec;

for actual_row in &rows {
    print!("row - ");
    
    for actual_number in actual_row {
        
        print!("n:{}",actual_number);
    }
    
    for actual_number2 in precedent_row{
        
        print!("n:{}",actual_number2);
    }
    precedent_row= &actual_row;
}

THE COMPILATION ERROR:
precedent_row= &actual_row;
| ^^^^^^^^^^^
| |
| expected struct std::vec::Vec, found reference
| help: try using a conversion method: &actual_row.to_vec()

Thanks in advance if you can help me with this error :slight_smile:

The first problem is that actual_row is &Vec, while precedent_row is Vec. (this is what the compilation error says). You can simply write
let precedent_row: &Vec<_>;
to fix this.
Also, you need to make it mutable:
let mut precedent_row: &Vec<_>;
Finally, what should precedent_row be in the first iteration? Use
let mut precedent_row: &Vec<_> = &Vec::new();
to make it an empty vec.

Or you use itertools::Itertools - Rust
for (precedent_row, actual_row) in rows.iter().tuple_windows()

thanks a lot this worked. my solution is with itertools!
after your help, I have a little refined my code that I share in case other newbie need the same:

use itertools::Itertools;

fn main() {
//create vectors of vectors
let mut rows: Vec<Vec<_>> = std::vec::Vec::new();
// create five rows
for iterate_rows in 0..5 {
let mut row: Vec = std::vec::Vec::new();
//put 10 numbers in each row
for iterate_numbers in 0..10 {
row.push(iterate_numbers+iterate_rows *10);
}
rows.push(row);
}

for (precedent_row, actual_row) in rows.iter().tuple_windows() {
    print!("row - ");

    for actual_number_precedent_row in precedent_row {
        print!("N:{} ", actual_number_precedent_row);
    }
    print! ("          ");
    for actual_number_actual_row in actual_row {
        print!("n:{} ", actual_number_actual_row);
    }

    println!();
}

}

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