Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip Vec<T> with indexed position

Tags:

rust

Following my question, How to iterate a Vec with indexed position in Rust, now I need to zip two dynamic vectors with their indexed position.

like image 242
bitloner Avatar asked Dec 03 '22 17:12

bitloner


1 Answers

The enumerate function exists for all iterators. Using zip on two iterators a and b yields another iterator. Therefor you can also call enumerate on the resulting iterator.

fn main() {
    let a = vec![1; 10];
    let b = vec![2; 10];

    let it = a.iter().zip(b.iter());

    for (i, (x, y)) in it.enumerate() {
        println!("{}: ({}, {})", i, x, y);
    }
}
like image 107
oli_obk Avatar answered Dec 05 '22 07:12

oli_obk